Why do I get an "invalid syntax" error for this simple if-else code?

Question:

I have a simple python code as follows:

a = 3

if a == 3:
  print("a is 3")

print("yes")

else:
  print("a is not 3")

I get an invalid syntax error for the else: part. Can someone please explain why? Is it illegal to have code between an if and else statement?

Asked By: penguin99

||

Answers:

It is not illegal. However, you have exited the if-else condition when you printed the word "yes" and there is no "if" to go with the "else" that follows it. I think you intended to indent the second print statement. That will certainly resolve the error anyway.

Answered By: Terry

This is expressly forbidden by the language definition. You cannot have an else without a matching if.

Note the syntax here is that you can have zero or more elif statements and else is entirely optional, if you don’t want to include it.

if_stmt ::=  "if" assignment_expression ":" suite
             ("elif" assignment_expression ":" suite)*
             ["else" ":" suite]

Depending on your actual goals here, you could do something where you just keep the print function call inside of the positive if block instead.

a = 3

if a == 3:
  print("a is 3")
  print("yes")
else:
  print("a is not 3")

…but this is obviated by "a is 3" being printed out in advance of this, so having this print("yes") expression doesn’t add a whole lot of extra value.

Answered By: Makoto
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.