-4
>>> x=[]
>>> for i in range(10):
     x.append(i)
print(x)
SyntaxError: invalid syntax

I'm working with Python 3.5. I can't seem to get the print function working when it's not part of a loop. "print" gets highlighted as the source of the syntax error, but I can't seem to isolate the cause of the error. It prints perfectly well when part of a while or for loop. It's probably caused by a really silly oversight, and I would really appreciate if somebody could point it out.

4
  • 1
    check the indentation. Nov 13, 2015 at 1:51
  • 1
    Python Shell hum? Did you try press some enter before print(x)?
    – Remi Guan
    Nov 13, 2015 at 1:51
  • Also, please paste full commands and the Traceback.
    – Remi Guan
    Nov 13, 2015 at 1:52
  • 1
    You need to press enter twice after the x.append(i). Once to end the line and another to end the suite of statements (one in this case) under control of the for loop.
    – martineau
    Nov 13, 2015 at 1:53

1 Answer 1

3

If you are typing in console, you need to hit enter twice to end that statement. Which in your case, what you did is, you wrote print inside for without indentation. So it will show syntax error.

This is how your code should look like !

2
  • Thank you so much! I didn't realise I couldn't just start a new statement by removing the indent. I heard that indentation is really important in Python, but I'm still somewhat at a loss as to how to use it properly. It's hard to get my head around Python when I'm used to the conventions of C.
    – rlrq
    Nov 14, 2015 at 4:15
  • Anytime bro :) ! If you are new to python, i will highly suggest you not to type directly in the python shell. Use any text editor and then save the program with .py extension and run it using $python3 filename.py Alternatively if you are in Linux, you can use geany ! Nov 14, 2015 at 7:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.