[英]Error in Python Tutorial Example Code?
I'm working my way through the python tutorial here and the following code is used as an example.我在这里完成 python 教程,以下代码用作示例。
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
When I run it in the Canopy editor though I get the following error message当我在 Canopy 编辑器中运行它时,虽然我收到以下错误消息
File "<ipython-input-25-224bab99ef80>", line 5
print(a, end=' ')
^
SyntaxError: invalid syntax
The syntax is the same across PyLab, using python in the command prompt, and the Canopy Editor so I can't see why it wouldn't just run... PyLab 的语法是相同的,在命令提示符中使用 python 和 Canopy 编辑器,所以我不明白为什么它不能运行......
You are trying to run that code with the wrong version of Python. 您正在尝试使用错误版本的Python运行该代码。 The example is using Python 3.x, where
print
is a function , not Python 2.x, where print
is a statement . 该示例使用的是Python 3.x,其中
print
是函数 ,而不是Python 2.x,其中print
是statement 。
Note that for this specific example, you can write the function like so: 请注意,对于此特定示例,您可以这样编写函数:
>>> def fib(n):
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print a,
... a, b = b, a+b
...
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>>
Nevertheless, it is still a good idea to upgrade your version of Python if you will be using Python 3.x throughout your tutorial. 尽管如此,如果您将在整个教程中使用Python 3.x,那么升级Python版本仍然是一个好主意。
>>> def fib(n):
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print a,
... a, b = b, a+b
...
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.