尽管满足条件,条件语句下的代码仍未执行

时间:2017-07-24 06:01:18

标签: python list if-statement

也许是因为我没有编写几天,但我不明白为什么这不起作用。在for循环中遇到if i == enemy_spaceship_index的条件,但是该条件if语句下面的代码没有执行。当我打印出列表时,它只给了我7个2。应该做的是打印6个2和3个。列表中3的位置由enemy_spaceship_index确定。任何帮助,将不胜感激。

enemy_spaceship_index = randint(0, 6)
appearancesLeft = []

for i in range(7):
        if i == enemy_spaceship_index:
            appearancesLeft.append(3)
        elif i != enemy_spaceship_index:
            appearancesLeft.append(2)

    print appearancesLeft

2 个答案:

答案 0 :(得分:1)

我认为你的缩进搞砸了。否则,它看起来像你的代码工作得很好......

>>> from random import randint
>>> for x in range(7): # test all possible values
...     enemy_spaceship_index = x
...     appearancesLeft = []
...     for i in range(7):
...         if i == enemy_spaceship_index:
...             appearancesLeft.append(3)
...         elif i != enemy_spaceship_index:
...             appearancesLeft.append(2)
...         print appearancesLeft
...
[3]
[3, 2]
[3, 2, 2]
[3, 2, 2, 2]
[3, 2, 2, 2, 2]
[3, 2, 2, 2, 2, 2]
[3, 2, 2, 2, 2, 2, 2]
[2]
[2, 3]
[2, 3, 2]
[2, 3, 2, 2]
[2, 3, 2, 2, 2]
[2, 3, 2, 2, 2, 2]
[2, 3, 2, 2, 2, 2, 2]
[2]
[2, 2]
[2, 2, 3]
[2, 2, 3, 2]
[2, 2, 3, 2, 2]
[2, 2, 3, 2, 2, 2]
[2, 2, 3, 2, 2, 2, 2]
[2]
[2, 2]
[2, 2, 2]
[2, 2, 2, 3]
[2, 2, 2, 3, 2]
[2, 2, 2, 3, 2, 2]
[2, 2, 2, 3, 2, 2, 2]
[2]
[2, 2]
[2, 2, 2]
[2, 2, 2, 2]
[2, 2, 2, 2, 3]
[2, 2, 2, 2, 3, 2]
[2, 2, 2, 2, 3, 2, 2]
[2]
[2, 2]
[2, 2, 2]
[2, 2, 2, 2]
[2, 2, 2, 2, 2]
[2, 2, 2, 2, 2, 3]
[2, 2, 2, 2, 2, 3, 2]
[2]
[2, 2]
[2, 2, 2]
[2, 2, 2, 2]
[2, 2, 2, 2, 2]
[2, 2, 2, 2, 2, 2]
[2, 2, 2, 2, 2, 2, 3]

答案 1 :(得分:0)

在这里,我为您修复了代码,现在正在运行:

    import random

    enemy_spaceship_index = random.randint(0, 6) 
    appearancesLeft = []

    for i in range(7):
            if i == enemy_spaceship_index:
                appearancesLeft.append(3)
            elif i != enemy_spaceship_index:
                appearancesLeft.append(2)

    print appearancesLeft

始终确保您保持正确的打算水平并导入所有库