Python if statement doesn't work as expected

2019-02-25 13:37发布

I currently have the code:

fleechance = random.randrange(1,5)
print fleechance
if fleechance == 1 or 2:
    print "You failed to run away!"
elif fleechance == 4 or 3:
    print "You got away safely!"

fleechance is constantly printing as 3 or 4, but I continue to get the result "You failed to run away!" ,can anyone tell me why this is happening?

5条回答
够拽才男人
2楼-- · 2019-02-25 14:22

Because you're not asking whether fleechance is 1 or fleechance is 2; you're asking whether

  1. fleechance is 1, or
  2. 2 is non-zero.

Of course, that second part of the condition is always true. Try

if fleechance == 1 or fleechance == 2:
    ...
查看更多
聊天终结者
3楼-- · 2019-02-25 14:31

Try

if fleechance == 1 or fleechance == 2:
    print "You failed to run away!"
elif fleechance == 4 or fleechance == 3:
    print "You got away safely!"

Alternatively, if those are the only possibilites, you can do

if fleechance <= 2:
    print "You failed to run away!"
else:
    print "You got away safely!"
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-25 14:33

The if statement is working as designed, the problem is that order of operations is causing this code to do something other than that you want.

The easiest fix would be to say:

if fleechance == 1 or fleechance == 2:
    print "You failed to run away!"
elif fleechance == 3 or fleechance == 4:
    print "You got away safely!"
查看更多
▲ chillily
5楼-- · 2019-02-25 14:35

The way you wrote your if statements is wrong. You tell python to check if fleechance equals 1 is true or if 2 is true. A non-zero integer always means true in a condition. You should wrote :

fleechance = random.randrange(1,5)
print fleechance
if fleechance == 1 or fleechance == 2:
    print "You failed to run away!"
elif fleechance == 4 or fleechance == 3:
    print "You got away safely!"
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-25 14:38

The expression fleechance == 1 or 2 is equivalent to (fleechance == 1) or (2). The number 2 is always considered “true”.

Try this:

if fleechance in (1, 2):

EDIT: In your situation (only 2 possibilities), the following will be even better:

if fleechance <= 2:
    print "You failed to run away!"
else:
    print "You got away safely!"
查看更多
登录 后发表回答