【发布时间】:2018-12-06 05:19:45
【问题描述】:
嗨,我是 python 新手,我搜索了一些小挑战来练习和了解更多信息,现在我正在做一个“猜数字”脚本,它有效,但现在我想添加一个 try/except当用户输入不是整数时阻塞,这是我现在拥有的代码:
from random import *
print('Guess the number')
def check_correct(u_guess, num):
while True:
if u_guess < num:
print('Guess is high!')
while True:
try:
u_guess = int(input('What number do you think is? (Between 1 and 5): '))
except ValueError:
print('Invalid number try again!')
elif u_guess > num:
print('Guess is low!')
while True:
try:
u_guess = int(input('What number do you think is? (Between 1 and 5): '))
except ValueError:
print('Invalid number try again!')
elif u_guess == num:
print('You got it!')
break
def guess():
num = randint(1, 5)
u_guess = None
while u_guess == None:
try:
u_guess = int(input('What number do you think is? (Between 1 and 5): '))
check_correct(u_guess, num)
except ValueError:
print('Invalid number try again!')
guess()
这是我的输出:
$ python Project2.py
Guess the number
What number do you think is? (Between 1 and 5): 1
Guess is high!
What number do you think is? (Between 1 and 5): 2
What number do you think is? (Between 1 and 5): 2
What number do you think is? (Between 1 and 5):
Invalid number try again!
What number do you think is? (Between 1 and 5): Traceback (most recent call last):
File "Project2.py", line 35, in <module>
guess()
File "Project2.py", line 31, in guess
check_correct(u_guess, num)
File "Project2.py", line 11, in check_correct
u_guess = int(input('What number do you think is? (Between 1 and 5): '))
EOFError
【问题讨论】:
-
您没有使用您的输入,而是再次请求输入。这是一个错误。退出你的函数,让外部 while 循环完成工作。
-
如前所述,您永远不会使用
break来退出无限重试循环。无论是否引发异常,您都会回到该循环的顶部。 -
但正如 deets 指出的那样,
check_correct做得太多了。它应该检查该值,输出猜测值是过高还是过低的描述,然后返回 True 或 False。guess是唯一真正应该接受用户输入的函数。
标签: python try-except