不理解错误消息:for语句中的语法无效

问题描述:

我正在写一个非常简单的程序,使用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'。 –

试试这样说:

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

这是for的错误语法。根据docs

for语句用于迭代序列(如字符串,元组或列表)或其他可迭代对象的元素。

这是不是你的情况下,也可以使用range()创建序列:

​​

但它是人造的解决方法,虽然它会工作,是不是你应该真正在做什么。

您应该使用while来代替。 Docs说:

while语句用于重复执行,只要一个表达式为真

while counter <= 9: 
+0

好的。谢谢 – Isaac

几个百分点。摘录如下:

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)