gpt4 book ai didi

Python 输入偏离第一个 if 语句

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:50 24 4
gpt4 key购买 nike

当我输入一个选项时,在它后面有几个“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 的关键字。

关于Python 输入偏离第一个 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19452287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com