python 3 try/except 退出而不是循环
python 3 try/except exiting rather than looping
我不确定我做错了什么。我试图将用户输入限制为 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 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")
因为您要在 Exception
退出循环。你应该写这样的代码:
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")
在 try 代码之前使用 while 循环,这将像这样继续循环 try 和 catch 块
while True:
try:
# Your Code
except ValueError:
# Your Code
我不确定我做错了什么。我试图将用户输入限制为 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 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")
因为您要在 Exception
退出循环。你应该写这样的代码:
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")
在 try 代码之前使用 while 循环,这将像这样继续循环 try 和 catch 块
while True:
try:
# Your Code
except ValueError:
# Your Code