我不理解这个语法错误的原因。

4

我正在尝试学习Python 2,但我没有任何计算机语言的背景。我正在使用“ByeofPython”教程。练习要求我们在编辑器(文本编译器)中输入以下内容:

#!/usr/bin/python
#Filename : helloworld.py
print "Hello World'

请将其保存为helloworld.py。我按照要求在桌面上的名为python练习的文件夹中完成了保存。

接下来,教程要求我们:

Run this program by opening a shell (Linux terminal or DOS prompt) and entering the command python helloworld.py. If you are using IDLE, use the menu Edit -> Run Script or the keyboard shortcut Ctrl-F5. The output is as shown below.

$ python helloworld.py
Hello World
然而,当我进入终端并输入“python helloworld.py”时,出现了以下情况。
python helloworld.py
                    ^
SyntaxError: invalid syntax

有人能告诉我错在哪吗?我觉得我输入的都正确。我使用的是 Mac 并运行 python 2.6。


10
你是不是在Python解释器里输入的这个? - Martijn Pieters
2个回答

4
你看到SyntaxError是因为引号不匹配。
你的print语句应该是:
print "Hello World"

print "Hello World'

9
是的,除此之外,但这并不是导致OP出现SyntaxError的原因...它与给出的回溯信息不匹配。 OP一直在Python shell或IDLE中输入命令。 - Martijn Pieters
谢谢指出。看起来你是对的,他的第一个错误是在Python解释器中输入“python helloworld.py”。 - Joe Day
不平衡的引号会导致 SyntaxError: EOL while scanning string literal - Martijn Pieters

1

你可能正在输入Python解释器,但你输入的命令不是有效的Python命令。 要退出这个模式,你可以按CTRL-D(文件结尾)或CTRL-C(中断程序)。

(我不确定这些键序列在Windows上是否相同)

如果你运行命令python而没有在它后面加上脚本文件的名称,它将开始读取用户输入,就好像它是一个Python程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接