2

Today I have been learning a "for loop" in Python. I type the code in Python Shell and SyntaxError: invalid syntax appears after the function print("I finished") with the word print in red.

words = ["cat", "125", "dog", "pig"]
for word in words:
    if word == "125":
        print("No spam please!")
        break
    print("Nice " + word)
else:
    print("I am lucky: No spam.")
print("I finished")

But when I write the code in Notepad and save as *.py and than run with Command Prompt it works correctly and comes:

Nice cat
No spam please!
I finished

What is with the third "print" function wrong?

2
  • I do not understand why does "invalid syntax" appear. In command prompt it works correctly. Commented Oct 8, 2014 at 18:24
  • you probably had some cr+lf mixed with some cr only end of lines. Notepad must have corrected this. Commented Oct 8, 2014 at 20:47

1 Answer 1

5

In interactive Python shells, you usually need to leave an empty line between the end of an outermost if/else/for/while/whatever block and the beginning of the next statement.

else: 
    print("I am lucky: No spam.") 

print("I finished")

As a simpler example: No empty line causes an error:

>>> if True:
...     print("!")
... print("finished")
  File "<stdin>", line 3
    print("finished")
        ^
SyntaxError: invalid syntax

Leaving an empty space causes it to work:

>>> if True:
...     print("!")
...
!
>>> print("finished")
finished

Generally speaking, try not to start new statements on "continuation lines" that begin with "...". Press Enter until you see ">>>", and then you're good to go.

Sign up to request clarification or add additional context in comments.

2 Comments

It really would have been better to show this in Python 3 instead of 2, because a novice using 3.x is likely to be confused your also-a-SyntaxError-in-3.x print statements.
I like the last sentence you added at the end, too. (The only problem is when you're trying to paste into the terminal, and you can't always avoid it… but if you're doing a lot of pasting into the terminal, you probably want IPython or an IDE anyway…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.