Error in Python Tutorial Example Code?

Question:

I’m working my way through the python tutorial here and the following code is used as an example.

>>> 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

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…

Asked By: Hugh_Kelley

||

Answers:

You are trying to run that code with the wrong version of Python. The example is using Python 3.x, where print is a function, not Python 2.x, where print is a 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.

Answered By: user2555451
>>> 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
Answered By: Mohamed Ghorbel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.