Python 3.x Python3尝试/除了退出而不是循环
我不确定我做错了什么。我正在尝试将用户输入限制为1-6(骰子游戏)。逻辑正在工作,但当引发ValueError()时,它不会再次提示用户Python 3.x Python3尝试/除了退出而不是循环,python-3.x,try-except,Python 3.x,Try Except,我不确定我做错了什么。我正在尝试将用户输入限制为1-6(骰子游戏)。逻辑正在工作,但当引发ValueError()时,它不会再次提示用户 try: while True: choice = input('Enter number to hold - type D to roll: ') print(choice) if choice == 'D': return choice_list elif le
try:
while True:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
因为您将在
异常退出循环。您应该编写如下代码:
while True:
try:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
因为您将在异常退出循环。您应该编写如下代码:
while True:
try:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
使用while-loop-beforetry代码,它将像这样循环try-and-catch块
while True:
try:
# Your Code
except ValueError:
# Your Code
使用while-loop-beforetry代码,它将像这样循环try-and-catch块
while True:
try:
# Your Code
except ValueError:
# Your Code
谢谢-非常有用谢谢-非常有用