L.T*_*SON 1 python string integer python-3.x
我需要代码能够接受整数和字符串版本1和2.我尝试在输入()上使用str()和int()但它不起作用,只接受整数形式1和2.如果用户的输入不是1,1,2或2,我需要退出游戏.任何帮助表示赞赏.
print ('\n If you want to play the first game, enter 1.')
print ('I you want to play the second game, enter 2.')
gamechoice = str(int(input('\nPlease select the difficulty of the game: '))).lower()
if gamechoice == 1 or 'one':
Firstgame()
elif gamechoice == 2 or 'two':
secondgame()
else:
print ('\nSorry i dont undrstand')
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
根据您似乎检查用户输入的方式,最好不要输入输入.
首先,删除输入中的所有类型转换:
gamechoice = input('\nPlease select the difficulty of the game: ')
Run Code Online (Sandbox Code Playgroud)
现在,无论用户输入什么,您将拥有的绝对是一个字符串.此时你应该做的是测试是否gamechoice匹配预期的值来切换适当的游戏.您可以使用in条件语句,如下所示:
if gamechoice.lower() in ('1', 'one'):
Firstgame()
elif gamechoice.lower() in ('2', 'two'):
secondgame()
Run Code Online (Sandbox Code Playgroud)