Why am I getting "SyntaxError:" on OS X Python 3.4?
I just got a brand new MackBook Pro and installed Python 3.4. I launched a terminal and typed
python3.4
I got:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
I typed:
>>> print("Hello world")
Hello world
Everything is fine, but when I tried to do something more complicated I ran into a problem, I did:
>>>counter = 5
>>>
>>> while counter > 0:
... counter -= 1
... print()
... print("Hello World")
I am getting the error:
File "<stdin>", line 4
print("Hello World")
^
SyntaxError: invalid syntax
I'm assuming the error is in 'print ("Hello World"), but I don't know why, I don't need to backtrack if I want it to run after the loop ends. Any help would be appreciated.
source to share
Notice the prompt "..."? This tells you that the interactive interpreter knows that you are in the block. You will need to enter a blank line to complete the block before making the final print statement. In the meantime, there is no need to know about it. ”
This is an artifact of working interactively - an empty line is not required when entering code into a file.
source to share
Because this is a syntax error.
>>> while counter > 0:
... counter -= 1
... print()
... print("Hello World")
this is how the python console works - you can see there are three dots before printing ("hello world"), indicating that python is still expecting indendted code that belongs to the block.
You need to press enter twice to go to normal mode. (Signalized by →>). Also in the future, if you face similar problems, always try to run them from a file, not just the console.
source to share
This is caused by a quirk of python interactive mode that handles newlines on purpose.
When you have a prompt ...
, it should be followed by a continuation of the previous compound statement, not the start of a new statement, which it will be in non-interactive mode. Press the key again to make the invitation ...
.
Observer that this fails:
echo $'while False: pass\npass' | python -i
But this works:
echo $'while False: pass\npass' | python
In the grammar link, you can read the details . An interactive input uses an initial state single_input
, and a non-interactive input uses an initial state file_input
.
source to share