Logical or operator not behaving as expected [duplicate]

若如初见. 提交于 2019-12-01 13:48:22

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':

and expand this to your other Choice1 tests.

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.

You have:

    if Choice1 == 'Life' or 'life':

Which is actually the equivalent of:

    if (Choice1 == 'Life') or 'life':

A non-empty/non-zero string ('life') will always be treated as true, hence why you end up there.

You either want:

    if Choice1 == 'Life' or Choice1 == 'life':

or:

    if Choice1.lower() == 'life':

Use in:

elif Choice1 in ('Pickup', 'pickup'):

Alternatively, you can use regular expressions:

import re

elif re.match("[Pp]ickup", Choice1):

Separately, I'd use a set for your inventory:

Inventory = set()
Squirrel =  'Squirrel'
while True:
...
        if p1 == Squirrel:
            if not Inventory:
                print'You picked up a Squirrel!'
                Inventory.add(Squirrel)
            elif Squirrel in Inventory:
                print'You already picked that up!'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!