2017-07-24 102 views
-1

也許這是因爲我沒有編碼幾天,但我不明白爲什麼這不起作用。在for循環中遇到if i == enemy_spaceship_index一次的條件,但該條件if語句下的代碼未執行。當我列出名單時,只給我七個二分。應該做的是打印六個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 

回答

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] 
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 

務必讓你保持打算水平右側和所有導入的庫

+1

您在「appearancesLeft = []」之前有一個缺失的換行符「 –

相關問題