-1

This might be a silly question, but I really don't know which part is wrong?

I wrote the following code:

b = 0
while b < 10:
    print(b, end=" ")
    b = b + 1

But I always got this error message:

  File "/Users/l/Desktop/test.py", line 3
    print(b, end=" ")
                ^
SyntaxError: invalid syntax

Could someone give me a little help? Thanks!

S. Li
  • 767
  • 1
  • 7
  • 14

4 Answers4

2

This syntax is valid only in Python3, you're probably using Python2.

Python3:

print("Hello World", end="!") # OUTPUT: Hello World!

Python2:

print("Hello World", end="!")

File "...\python test.py", line 5 print("Hello World", end="!") SyntaxError: invalid syntax

Gsk
  • 2,929
  • 5
  • 22
  • 29
  • Are you using sublime text? if so, you can have both python working, you just choose which one will compile – Gsk Jun 26 '18 at 08:22
  • Yes, I am using sublime text. It's just... I am still not very familiar with it. – S. Li Jun 26 '18 at 08:28
  • check [this question](https://stackoverflow.com/questions/40024713/possible-to-switch-between-python-2-and-3-in-sublime-text-3-build-systems-wind/40031389#40031389) or open a different one for enable both python versions in sublime text – Gsk Jun 26 '18 at 09:24
2

As already mentioned, this is a Python3 feature, but you can emulate this behavior in Python2 as well, like this:

from __future__ import print_function

print('Now it works', end='!')

See this link for more on future imports.

Arno-Nymous
  • 495
  • 3
  • 14
1

Python 2 and 3

from __future__ import print_function

b = 0
while b < 10:
    print(b, end=" ")
    b = b + 1
hootnot
  • 1,005
  • 8
  • 13
  • I just tried. This works. And I now know the problem is due to my python version. I might need to change some settings of my text editor. Thanks. – S. Li Jun 26 '18 at 08:25
1

In python 3 your code will work fine, but in python 2 do this :

b = 0
while b < 10:
  print b ,  #put comma at end 
  b = b + 1

0 1 2 3 4 5 6 7 8 9
Nidhin Sajeev
  • 562
  • 4
  • 11