如果输入是非法的,则在给定的尝试中继续请求输入

  • 本文关键字:继续 请求 非法 如果 python
  • 更新时间 :
  • 英文 :


如果用户没有输入数值,我如何让他们继续尝试为特定的尝试输入数字?例如,如果他们没有为第2次尝试输入数字,他们是否可以继续为这次尝试输入值?

correct_number = 7
for x in range(1, 4):
try:  
user_guess = int(input('Attempt ' + str(x) + ': '))
except ValueError:
print('You did not enter a numerical value for year.')
break

if user_guess == 7:
print('Good job!')
break

我们添加了一个初始化为False的标志is_number_given

当我们从用户那里获得价值时,要么:

  1. 这不是一个数字,引发了一个异常,is_number_given标志保持为False,所以我们一直要求一个值
  2. 给定的值是一个数字,我们将is_number_given标志设置为True并结束此尝试会话
correct_number = 7
for x in range(1, 4):
user_guess = None
is_number_given = False
while not is_number_given:
try:
user_guess = int(input('Attempt ' + str(x) + ': '))
is_number_given = True
except ValueError:
print('You did not enter a numerical value for year.')
# Better use `user_guess == correct_number`
# so there is one place in code where `correct_number` value exists
if user_guess == 7:
print('Good job!')
break

最好使用while循环,然后使用continue返回尝试尝试此代码其工作:在此处输入代码:其工作完美:点击此处

最新更新