Skip to main content
 首页 » 编程设计

Python 输入偏离第一个 if 语句

2025年05月04日1152php

当我输入一个选项时,在它后面有几个“if”语句,除了第一个语句之外的所有其他“if”语句都被忽略。 例如:

print('1. dostuff') 
print('2. stuff') 
choice = input('What do you want to do? ') 
if choice == '1' or 'dostuff': 
    domorestuff() 
if choice == '2' or 'stuff': 
    stuff() 

无论我输入什么,它都会转到“domorestuff()”。

请您参考如下方法:

应该是:

if choice in ('1', 'dostuff'): 

现在,Python 正在像这样读取您的代码:

if (choice == '1') or 'dostuff': 

这意味着它将总是返回True 因为"dostuff" 总是评估为True 因为它是一个非空字符串。请参阅下面的演示:

>>> choice = None 
>>> choice == '1' or 'dostuff' 
'dostuff' 
>>> bool(choice == '1' or 'dostuff') 
True 
>>> 

然而,我给出的解决方案使用了 in用于测试是否可以在元组 ('1', 'dostuff') 中找到 choice 的关键字。