Python初学者:导入程序时出现<Syntaxerror: invalid syntax>

2 投票
2 回答
6303 浏览
提问于 2025-04-17 16:11

这是我学习编程的第一天。我正在跟着John Zelle的《Python编程:计算机科学导论(第二版)》学习,到目前为止一切都很顺利。

唯一的问题是,当我尝试导入一个保存好的程序时,出现了语法错误。我先写好程序并保存,然后再执行,但当我尝试导入时就出错了。我还试着打开一个新的命令行窗口,但还是不行。我使用的是OSX Lion 10.8和Python 2.7.3。希望能得到一些帮助。这就是问题的表现:

>>> #File: chaos.py
>>> #A simple program illustrating chaotic behavior.
>>> def main():
    print "This program illustrates a chaotic function"
    x=input("Enter a number between 0 and 1: ")
    for i in range(10):
        x = 3.9 * x * (1-x)
        print x


>>> main()
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>> import chaos

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    import chaos
  File "chaos.py", line 1
    Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43)
             ^
SyntaxError: invalid syntax

2 个回答

1

我猜测你是在把终端里的内容直接复制到文件里。这样做的话,里面会有很多不应该出现的东西,比如说版本提示

文件里应该只包含类似这样的内容:

#File: chaos.py
#A simple program illustrating chaotic behavior.
def main():
    print "This program illustrates a chaotic function"
    x=input("Enter a number between 0 and 1: ")
    for i in range(10):
        x = 3.9 * x * (1-x)
        print x

里面不要有>>>,也不要有...,更不要有制表符,当然也不要复制版本信息:

Python 2.7.3 (default, Dec 22 2012, 21:27:36) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
1
  File "chaos.py", line 1
    Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43)
             ^
SyntaxError: invalid syntax

看起来你的 chaos.py 脚本的第一行有一段不是Python代码:

Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43)

这行代码应该被删除,或者在行首加一个 # 符号来注释掉它。


这里有一些小贴士供你参考:

  • 在Python中,空格是很重要的——它们表示缩进的层级。不要混用空格和制表符,否则Python会报 IndentationError 错误。
  • 在文本或网页中,你可能会看到一些交互式会话的记录,其中包含 >>>...,这表示Python的提示符或缩进层级。如果你把代码转移到脚本中,必须把这些去掉。

撰写回答