如何为无效输入添加例外?

时间:2016-10-21 19:26:44

标签: python exception input

我是Python的新手,所以这对许多人来说可能是一个愚蠢的问题,但是在下面的代码中,我将如何添加异常,以便有人输入例如一个单词,这将处理输入无效并继续询问,'猜猜。'?

import random
secretNumber = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')

for guessesTaken in range(1, 11):
    print('Take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break   # This condition is the correct guess!

if guess == secretNumber:
    print('Good job! You guessed mu number in ' + str(guessesTaken) + ' guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))

1 个答案:

答案 0 :(得分:0)

我相信你想要做的事情可以通过如下输入完成:

guess = None
while guess is None:
    try: 
        print('Take a guess.')
        guess = int(input())
    except ValueError:
        pass