2017-08-17 90 views
-3

我正在寫一個非常簡單的程序,使用for循環輸出數字0-10。然而,當我點擊運行時,會出現語法錯誤,在第8行中用紅色突出顯示「=」。我不明白爲什麼它是錯的?我在空閒模式下使用python 3.5.2。不理解錯誤消息:for語句中的語法無效

def numbers(): 
    print ("This program will count to ten, just you wait...") 
    import time 
    time.sleep(1) 
    print ("\n\nLiterally wait I just need to remember base 10 because I 
    only work in binary!") 
    time.sleep(4) 
    int(counter) = 0 
    for counter <**=** 9: 
    print ("\n" + counter) 
    counter = counter + 1 

    print ("\n\nAnd there you go. Told you I could do it. Goodbye :) ") 
    time.sleep(2) 
    exit() 

numbers() 
+0

你'for'聲明是無效的。您正在尋找'while',或[Python文檔](http://python.org)。 –

+1

'int(counter)= 0'是什麼意思?這是無效的Python語法。它應該讀'counter = 0'。 –

回答

0

試試這樣說:

def numbers(): 
    print ("This program will count to ten, just you wait...") 
    import time 
    time.sleep(1) 
    print ("\n\nLiterally wait I just need to remember base 10 because I only work in binary!") 
    time.sleep(4) 
    for i in range(1, 10): #11 if you want 10 to be printed 
     print i 

    print ("\n\nAnd there you go. Told you I could do it. Goodbye :) ") 
    time.sleep(2) 
+0

看起來不錯,我會試試看。謝謝! – Isaac

+0

它工作/謝謝你... – Isaac

+0

@Isaac歡迎您,請接受答案 – zipa

0

這是for的錯誤語法。根據docs

for語句用於迭代序列(如字符串,元組或列表)或其他可迭代對象的元素。

這是不是你的情況下,也可以使用range()創建序列:

​​

但它是人造的解決方法,雖然它會工作,是不是你應該真正在做什麼。

您應該使用while來代替。 Docs說:

while語句用於重複執行,只要一個表達式爲真

while counter <= 9: 
+0

好的。謝謝 – Isaac

0

幾個百分點。摘錄如下:

int(counter) = 0 
for counter <**=** 9: 
print ("\n" + counter) 
counter = counter + 1 

有多個錯誤。

  1. int(counter) = 0是無效的Python語法。
  2. for counter <**=** 9不是有效的for聲明。
  3. print ("\n" + counter)counter = counter + 1缺乏正確的縮進。

取代那些4行

for counter in range(10): 
    print(counter)