TAGS :Viewed: 14 - Published at: a few seconds ago

[ Python print function invalid syntax with parenthesis ]

I am new to Python and I am using a Raspberry Pi with Python 3.2.3. I have been following a short tutorial on making games (in this case, creating the game Mastermind) and I have encountered a problem with the print function even though I am using parentheses at the start and end of the line. The line goes as follows:

print("I've selected a 4-character secret code from the letters A,B,C,D,E and F.")

Invalid syntax is highlighting the print function and I am unsure how to fix the fault.

Edit: Yes the fault is the previous line as I did not put an end bracket on.Here is the line right now:

secret = [random.choice('ABCDEF') for item in range (4)

I did not put a ']' at the line, I have now done so and the invalid syntax has been solved. Thank you very much for helping me! :)

Answer 1


Your syntax error is most likely on the line before your print function (I'm betting on a missing closing parenthesis.

Python only notices this when it has reached the next line which appears not to make any sense because Python is still trying to logically fit it into the previous line...

>>> print("Hello"
... print("Hello again")
  File "<stdin>", line 2
    print("Hello again")
        ^
SyntaxError: invalid syntax

Answer 2


maybe you didn't close brackets in the line before this one. it can be like this:

print("hello"
print("I've selected a 4-character secret code from the letters A,B,C,D,E and F.")

the computer will say "Invalid syntax" on the letter before the opening brackets of the second print line.

line 2
    print("I've selected a 4-character secret code from the letters A,B,C,D,E and F.")
        ^
SyntaxError: invalid syntax

Answer 3


You are probably trying things out in the interactive shell and you probably have a function before it. For example:

>>> def f():
...     pass
... print("I've selected a 4-character secret code from the letters A,B,C,D,E and F.")
  File "<stdin>", line 3
    print("I've selected a 4-character secret code from the letters A,B,C,D,E and F.")
        ^
SyntaxError: invalid syntax
>>>

You need to press Enter one more time to prevent this from happening:

>>> def g():
...     pass
...
>>> print("I've selected a 4-character secret code from the letters A,B,C,D,E and F.")
I've selected a 4-character secret code from the letters A,B,C,D,E and F.