1

When I input a choice, with a couple of 'if' statements after it, all the other 'if' statements except for the first one is ignored. For example:

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()

Whatever I input, it will always go to 'domorestuff()'.

4

2 回答 2

7

它应该是:

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关键字来测试是否choice可以在 tuple 中找到('1', 'dostuff')

于 2013-10-18T14:35:32.860 回答
3

这是一个非常常见的错误。它应该是这样的:

if choice == '1' or choice == 'dostuff':
       domorestuff()
if choice == '2' or choice == 'stuff':
       stuff()

您需要重申choice ==. 照原样,情况被视为:

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

这将永远是真实的,因为'dostuff'它是真实的。

于 2013-10-18T14:35:06.003 回答