如果用户没有输入数值,我如何让他们继续尝试为特定的尝试输入数字?例如,如果他们没有为第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
。
当我们从用户那里获得价值时,要么:
- 这不是一个数字,引发了一个异常,
is_number_given
标志保持为False,所以我们一直要求一个值 - 给定的值是一个数字,我们将
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
返回尝试尝试此代码其工作:在此处输入代码:其工作完美:点击此处