Issue
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...
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.