Python 键入'的编码错误消息;输入';
假设你被要求输入,比如你的年龄,但是你没有输入你的年龄,而是意外地点击了“回车”。然而,程序忽略了按键并进入下一步。您的年龄未输入,但被视为空/空值 如何编写代码来解决此问题 多谢各位Python 键入'的编码错误消息;输入';,python,null,Python,Null,假设你被要求输入,比如你的年龄,但是你没有输入你的年龄,而是意外地点击了“回车”。然而,程序忽略了按键并进入下一步。您的年龄未输入,但被视为空/空值 如何编写代码来解决此问题 多谢各位 age = raw_input("Age: ") while not age: # In Python, empty strings meet this condition. So does [] and {}. :) print "Error!" age = raw_input("Age:
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
然后:
使用
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
请显示用于从用户获取输入的代码-
raw\u input
或input
?而Python2.X或3呢?问题非常类似于:如果值无效,您必须验证该值并以某种方式让用户知道/重新编译。如何做到这一点取决于您首先如何提示用户(控制台、GUI等)。
while True:
try:
age = int(input('>> Age: '))
except ValueError:
print('Incorrect input')
continue
else:
break