逻辑或运算符的行为不符合预期 [英] Logical or operator not behaving as expected
问题描述
def Forest(Health,Hunger):
print'You wake up in the middle of the forest'
Inventory = 'Inventory: '
Squirrel = 'Squirrel'
while True:
Choice1 = raw_input('You...\n')
if Choice1 == 'Life' or 'life':
print('Health: '+str(Health))
print('Hunger: '+str(Hunger))
elif Choice1 == 'Look' or 'look':
print 'You see many trees, and what looks like an edible dead Squirrel, \na waterfall to the north and a village to the south.'
elif Choice1 == 'Pickup' or 'pickup':
p1 = raw_input('Pickup what?\n')
if p1 == Squirrel:
if Inventory == 'Inventory: ':
print'You picked up a Squirrel!'
Inventory = Inventory + Squirrel + ', '
elif Inventory == 'Inventory: Squirrel, ':
print'You already picked that up!'
else:
print"You can't find a "+str(p1)+"."
elif Choice1 == 'Inventory' or 'inventory':
print Inventory
我试图这样做,当它说
你......
你可以输入Life,Pickup,Look或Inventory。
我在这个程序上有更多的代码我只是向你展示一部分。
但是每次运行它时,即使您键入Pickup或Look或Inventory,它也始终显示Life部分。
请帮忙!
谢谢,
John
I am trying to make it so when it says You... you can type either Life, Pickup, Look, or Inventory. I have way more code on this program I am just showing you a portion. But every time I run it, it always shows the "Life" portion even if you type "Pickup" or "Look" or "Inventory". Please help! Thanks, John
编辑:
我认为这只是一个间距问题,但我不确定它早先运行良好。 ..
I think it's just a spacing issue but I am not sure it was running fine earlier...
推荐答案
您误解或
表达式。改为使用它:
You are misunderstanding the or
expression. Use this instead:
if Choice1.lower() == 'life':
或者,如果您必须针对多个选项进行测试,请在中使用:
or, if you must test against multiple options, use in
:
if Choice1 in ('Life', 'life'):
或者,如果你必须使用或
,那么就这样使用它:
or, if you must use or
then use it like this:
if Choice1 == 'Life' or Choice1 == 'life':
并将其展开到您的其他 Choice1
测试。
and expand this to your other Choice1
tests.
Choice1 =='Life'或'life'
被解释为(Choice1 =='Life')或('life')
,后一部分总是为True。即使它被解释为 Choice1 ==('生命'或'生命')
,那么后者将评估为'Life'
only(布尔测试时为True),所以你要测试 Choice1 =='Life'
相反,将选择
设置为'life'
将永远不会让测试通过。
Choice1 == 'Life' or 'life'
is interpreted as (Choice1 == 'Life') or ('life')
, with the latter part always being True. Even if it was interpreted as Choice1 == ('Life' or 'life')
then the latter part would evaluate to 'Life'
only (it being True as far as boolean tests go), so you'd be testing if Choice1 == 'Life'
instead, and setting Choice
to 'life'
would never make the test pass.
这篇关于逻辑或运算符的行为不符合预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!