Python:为错误的IF条件分配值

时间:2013-06-12 05:11:26

标签: python variables if-statement

我正在搞乱Python并正在制作一个小行星模拟器。我有一个部分应该接收一个值,并根据该值返回第二个值。我花了几个小时来解决这个问题,但我绝对难过。我添加了一些打印消息,以帮助我跟踪值,它似乎应该工作,但事实并非如此。我几乎可以肯定这是显而易见的事情。我做错了什么?

以下是相关代码:

def assignTerrain(pType):

print("Assigning terrain values to planet type: ", planetType[pType], pType)

if pType == 0:
    print("Value 0 assigned", pType)
    return 0

if pType == 1 or 2:
    temp = random.randint(1, 11)
    print("Value %d assigned" % temp, pType)
    return temp

if pType == 3 or 4:
    print("Value 12 assigned", pType)
    return 12

print("There was an error with pType: ", pType)

作为示例,以下是我得到的输出示例:

Assigning terrain values to planet type:  Asteroid Belt 4
Value 3 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 5 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 4 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 7 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 8 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 2 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 4 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 1 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 9 assigned 4
Assigning terrain values to planet type:  Asteroid Belt 4
Value 8 assigned 4

在我看来,pType 4应该跳过前两个IF语句并从第三个接收一个值,但它看起来好像被1或2捕获。任何想法?

2 个答案:

答案 0 :(得分:3)

而不是

pType == 1 or 2 

尝试

if pType in (1, 2) 

if pType == 1 or pType == 2. 

Python中的比较器不像你想象的那样工作。你在做什么实际上评估为

if ((pType == 1) or (4))

其中,因为4是真实的,所以总是真的。

答案 1 :(得分:2)

表达式pType == 1 or 2是两个表达式pType == 1的逻辑联合,可以是TrueFalse2,它始终是True {1}}到Python。因此,无论pType == 1 or 2的值如何,表达式True始终为pType