Skip to main content
 首页 » 编程设计

python之如何让 python 3 接受整数和字符串答案

2025年05月04日16pander-it

我需要代码能够接受 1 和 2 的整数和字符串版本。我尝试在 input() 上使用 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) 

请您参考如下方法:

根据您检查用户输入的方式,最好不要对输入进行类型转换。

首先,删除输入中的所有类型转换:

gamechoice = input('\nPlease select the difficulty of the game: ') 

现在,无论用户输入什么,您将拥有的绝对是一个字符串。此时您应该做的是测试 gamechoice 是否与预期值匹配以切换适当的游戏。您可以像这样在条件语句中使用 in:

if gamechoice.lower() in ('1', 'one'): 
     Firstgame() 
elif gamechoice.lower() in ('2', 'two'): 
     secondgame()