假设您被要求输入,例如您的年龄,但您没有输入您的年龄,而是不小心按了“输入”。但是,该程序会忽略击键并进入下一步。您的年龄未输入,但被视为空/空值。
你如何编码来解决这个问题?
谢谢
age = raw_input("Age: ")
while not age: # In Python, empty strings meet this condition. So does [] and {}. :)
print "Error!"
age = raw_input("Age: ")
您可以为此创建一个包装函数。
def not_empty_input(prompt):
input = raw_input(prompt)
while not input: # In Python, empty strings meet this condition. So does [] and {}. :)
print "Error! No input specified."
input = raw_input(prompt)
return input
然后:
address = not_empty_input("Address: ")
age = not_empty_input("Age: ")
使用while
循环,您不需要编写input()
两次函数:
while True:
age = input('>> Age: ')
if age:
break
print('Please enter your age')
您还可以检查输入是否为整数并从字符串中获取整数。空字符串age
也会引发ValueError
异常:
while True:
try:
age = int(input('>> Age: '))
except ValueError:
print('Incorrect input')
continue
else:
break