今天我一直在学习Python中的"for循环".我在Python Shell中键入代码,并SyntaxError: invalid syntax在函数后面显示红色print("I finished")单词print.
words = ["cat", "125", "dog", "pig"]
for word in words:
if word == "125":
print("No spam please!")
break
print("Nice " + word)
else:
print("I am lucky: No spam.")
print("I finished")
Run Code Online (Sandbox Code Playgroud)
但是当我在记事本中编写代码并保存为*.py和使用命令提示符运行时,它可以正常工作并且来:
Nice cat
No spam please!
I finished
Run Code Online (Sandbox Code Playgroud)
第三个"打印"功能错误是什么?
在交互式Python shell中,通常需要在最外层的if/else/for/while/whatever块的末尾和下一个语句的开头之间留一个空行.
else:
print("I am lucky: No spam.")
print("I finished")
Run Code Online (Sandbox Code Playgroud)
作为一个更简单的例子:没有空行会导致错误:
>>> if True:
... print("!")
... print("finished")
File "<stdin>", line 3
print("finished")
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
留空空间会导致它工作:
>>> if True:
... print("!")
...
!
>>> print("finished")
finished
Run Code Online (Sandbox Code Playgroud)
一般来说,尽量不要在以"......"开头的"延续线"上开始新的陈述.按Enter直到看到">>>",然后你就可以开始了.