0

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

Hugh_Kelley
  • 988
  • 1
  • 9
  • 23

2 Answers2

3

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.

  • Thanks, Strongly suggest switching to Python 3? I'm using "Python for Data Analysis" which is geared toward 2.x I believe. – Hugh_Kelley Jun 29 '14 at 17:36
  • Well, that depends on what you want to do. If you are learning Python for a specific thing that requires Python 2.x, then I would stay with Python 2.x. But if you are trying to learn Python in general, then I would upgrade and use the new, improved version. Remember that Python 2.x, like Python 1.x, will become entirely obsolete someday. You don't want to become an expert in something that is no longer used. :) –  Jun 29 '14 at 17:39
  • http://stackoverflow.com/questions/16142764/python-3-3-in-enthought-canopy. Seems like this is still true? – Hugh_Kelley Jun 29 '14 at 18:59
-1
>>> 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
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31622860) – Patrick Yoder May 02 '22 at 06:56