Python初学者:在尝试导入程序时

2024-05-19 12:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

唯一的问题是,当我尝试导入一个保存的程序时,我会得到一个syntaxerror。我编写程序并在执行之前保存它,但是当我尝试导入它时,我得到了错误。我试着打开一个新的贝壳,但没有雪茄。我使用的是OSXLion10.8和Python2.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

Tags: andpynumbermain编程functionbetweenthis
2条回答

我猜你是在把终端的内容一字不差地复制到文件中。还有很多不应该出现的东西,包括版本提示

文件应该有如下内容:

#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.
  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引发IndentationErrors
  • 在文本或网页中,您可以看到交互式 包括指示Python提示或 缩进水平。如果将代码转换为脚本,则必须 把那些拿走。

相关问题 更多 >