输入时编码错误消息

2024-05-01 02:08:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你被要求输入,比如你的年龄,但是你没有输入你的年龄,而是意外地按了回车键。然而,程序忽略了按键并进入下一步。您的年龄未输入,但被视为空/空值。你知道吗

如何编写代码来解决此问题?你知道吗

谢谢


Tags: 代码程序按键空值年龄回车键
2条回答

对于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
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: ")

相关问题 更多 >