或者和陈述,正确的方法

时间:2012-03-06 03:14:05

标签: python

所以我有代码:

if bulletaloc == bulletcount or bulletbloc == bulletcount and bulletcount % 2 == 0:
        print("Ow!", paname + "'s guts were spilled all over the floor")
 if bulletaloc == bulletcount or bulletbloc == bulletcount and bulletcount % 2 == 1:
        print("Whoops!", pbname, "just got killed...")

我想要它做的是当bulletaloc == bulletcount或当bulletbloc == bulletcount,AND时,这适用于两个条件......当bulletcount%2 == 9时,打印第一条消息。因此,当前两个语句中的任何一个为真时(bulletaloc ...和bulletbloc ...,并且第三个为真,请打印该消息。) 无论如何,最终发生的是两条消息都打印出来!我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

您应该了解orand的优先顺序:

>>> True or False and False
True
>>> (True or False) and False
False
>>> True or (False and False)
True

我会像这样重构它:

if bulletcount in (bulletaloc, bulletbloc):
  if bulletcount % 2:
    print("Whoops! {} just got killed...".format(pbname))
  else:
    print("Ow! {}'s guts were spilled all over the floor".format(paname))