在if语句上循环以拒绝无效输入

时间:2014-04-30 00:49:07

标签: python validation if-statement while-loop

在python中有没有办法重做原始输入和if语句,如果答案无效?

例如,如果您要求用户猜测1或2,并且他们猜测3您创建了额外的elif,或者告诉用户答案是无效的并再次通过raw input / if语句?

2 个答案:

答案 0 :(得分:1)

我相信你想要这样的东西:

# Loop until a break statement is encountered
while True:
    # Start an error-handling block
    try:
        # Get the user input and make it an integer
        inp = int(raw_input("Enter 1 or 2: "))
    # If a ValueError is raised, it means that the input was not a number
    except ValueError:
        # So, jump to the top of the loop and start-over
        continue
    # If we get here, then the input was a number.  So, see if it equals 1 or 2
    if inp in (1, 2):
        # If so, break the loop because we got valid input
        break

参见下面的演示:

>>> while True:
...     try:
...         inp = int(raw_input("Enter 1 or 2: "))
...     except ValueError:
...         continue
...     if inp in (1, 2):
...         break
...
Enter 1 or 2: 3
Enter 1 or 2: a
Enter 1 or 2: 1
>>>

答案 1 :(得分:0)

使用while声明:

try:
    x = int(raw_input('Enter your number: '))
except ValueError:
    print 'That is not a number! Try again!'
while x != 1 and x != 2:
    print 'Invalid!'
    try:
        x = int(raw_input('Enter your number: '))
    except ValueError:
        print 'That is not a number! Try again!'

此代码以必要的输入开始。然后,使用while循环,检查x是否为1或2.如果不是,我们进入while循环并再次请求输入。

你也可以这样做:

while True:
    try:
        x = int(raw_input('Enter your number: '))
    except ValueError:
        print 'That is not a number! Try again!'
    if x in [1, 2]:
        break