不明白错误消息:for语句中的语法无效

时间:2017-08-17 13:41:02

标签: python for-loop numbers syntax-error equals

我正在编写一个非常简单的程序,使用for循环输出0-10的数字。但是,当我单击运行时会出现语法错误,在第8行中以红色突出显示“=”。我不明白为什么这是错的?我在空闲模式下使用python 3.5.2。

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()

3 个答案:

答案 0 :(得分:0)

这是for的错误语法。根据{{​​3}}:

  

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

这不是您的情况,或者您可以使用range()创建序列:

for i in range(1, 10):

然而它的人工解决方法虽然有效,但不是你应该做的事情。

您应该使用while代替。 docs说:

  

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

while counter <= 9:

答案 1 :(得分: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)

答案 2 :(得分:0)

有几点。摘录:

.

有多个错误。

  1. int(counter) = 0 for counter <**=** 9: print ("\n" + counter) counter = counter + 1 不是有效的python语法。
  2. int(counter) = 0不是有效的for counter <**=** 9声明。
  3. forprint ("\n" + counter)缺少适当的缩进。
  4. 替换这四行
    counter =  counter + 1