3

I am beginner in python. I want to run this programmer in console but it's show me error what wrong in it.

>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...             print (a, end=' ')
  File "<stdin>", line 4
    print (a, end=' ')
                  ^
SyntaxError: invalid syntax

my actual program, which i want to run:

>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
>>> fib(1000)
Harman
  • 1,703
  • 5
  • 22
  • 40
  • 4
    It looks like you're running Python 3 code in Python 2. Either install Python 3, or find some tutorials/sample code that uses Python 2. – BrenBarn Jul 16 '14 at 04:15
  • 2
    You could also use `from __future__ import print_function` to make this particular example run. There may be other Python 3.x specific code in the example that isn't backported, though. – dano Jul 16 '14 at 04:19

1 Answers1

5

You are trying to run a Python3 code in Python2. The Python2 print is a keyword and just prints what's given, whereas the Python3 print is a function with some additional parameters. Python3 print was backported to Python2 and you can made it available using from __future__ import print_function:

>>> from __future__ import print_function
>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
... 
>>> fib(5)
0 1 1 2 3 

In plain Python2 it would look like this:

>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...         print a, ' '
...         a, b = b, a + b
...     print
... 
>>> fib(5)
0  
1  
1  
2  
3 

Unfortunately, Python2 print writes a newline at the end if you don't print a dot (print 1, 'something', '.'). See How to print without newline or space? for ways to go around it.

Or you could just store the results and then concatenate and print them at once, e.g.:

>>> def fib(n):
...     a, b = 0, 1
...     results = []
...     while a < n:
...         result.append(a)
...         a, b = b, a + b
...     print ' '.join([str(r) for r in results])
... 
>>> fib(5)
0 1 1 2 3
Community
  • 1
  • 1
famousgarkin
  • 13,687
  • 5
  • 58
  • 74