[英]Input from the use in a try/except block
i want to let the user type 1, 2 or quit otherwise i want to put him to type again one of them.我想让用户输入 1、2 或退出,否则我想让他再次输入其中一个。 everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level.一切都适用于 1 和 2,但 quit 不起作用,我也想如果他键入 quit 以使用 sys.exit('message') - 这部分来自 function,您可以在其中选择您的难度级别。 also its a hangman game.这也是一个刽子手游戏。 tanks坦克
Sloved!!爱了!!
import sys while True:在 True 时导入 sys:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower() try: difficulty = input("选择难度 1 为简单 2 为困难:").lower() try:
if difficulty == '1':
print('Easy game mode is set!')
elif difficulty =='2':
print('Hard game mode is set!')
elif difficulty =='quit':
print('Sheeeeeeeeeeeeeeesh')
except:
continue
if difficulty == '1' or difficulty =='2':
break
elif difficulty == 'quit':
sys.exit('byeeeee')
break
#elif difficulty
else:
print('invalid ')
You are storing the user input in uppercase for difficulty variable.您正在为难度变量以大写形式存储用户输入。 And in if condition verifying in lowercase.并在 if 条件下以小写形式验证。 So remove the upper()
from input("Choose difficulty 1 for easy 2 for hard: ").upper()
所以从input("Choose difficulty 1 for easy 2 for hard: ").upper()
upper()
try:
and except:
is probably not what you want to use here because you won't get a ValueError
and thus the except does not execute. try:
和except:
可能不是您想在这里使用的,因为您不会得到ValueError
,因此 except 不会执行。 Maybe try something like:也许尝试类似的东西:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
It breaks the loop when the correct input is given, and keeps looping otherwise.当给出正确的输入时它会中断循环,否则会继续循环。
If you would LIKE to have a ValueError when they enter a wrong input you can use raise
like so:如果你想在输入错误时出现 ValueError,你可以像这样使用raise
:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
raise ValueError #notice the additional line here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.