我正在编写一个接受用户输入的程序。
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
只要用户输入有意义的数据,程序就能正常工作。
Please enter your age: 23
You are able to vote in the United States!
但如果用户输入无效数据,则失败:
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in <module>
age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'
而不是崩溃,我希望程序再次要求输入。是这样的:
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!
我如何要求有效输入而不是崩溃或接受无效值(例如-1)?
使用“while”语句,直到用户输入一个真值,如果输入值不是一个数字或它是一个空值跳过它,并尝试再次询问,等等。
举例来说,我试图真正地回答你的问题。如果我们假设我们的年龄在1到150之间,那么输入值被接受,否则它是一个错误的值。
对于终止程序,用户可以使用0键并输入它作为一个值。
注意:阅读代码顶部的注释。
# If your input value is only a number then use "Value.isdigit() == False".
# If you need an input that is a text, you should remove "Value.isdigit() == False".
def Input(Message):
Value = None
while Value == None or Value.isdigit() == False:
try:
Value = str(input(Message)).strip()
except Exception:
Value = None
return Value
# Example:
age = 0
# If we suppose that our age is between 1 and 150 then input value accepted,
# else it's a wrong value.
while age <=0 or age >150:
age = int(Input("Please enter your age: "))
# For terminating program, the user can use 0 key and enter it as an a value.
if age == 0:
print("Terminating ...")
exit(0)
if age >= 18 and age <=150:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
使用递归函数的持久用户输入:
字符串
def askName():
return input("Write your name: ").strip() or askName()
name = askName()
整数
def askAge():
try: return int(input("Enter your age: "))
except ValueError: return askAge()
age = askAge()
最后,问题要求:
def askAge():
try: return int(input("Enter your age: "))
except ValueError: return askAge()
age = askAge()
responseAge = [
"You are able to vote in the United States!",
"You are not able to vote in the United States.",
][int(age < 18)]
print(responseAge)