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

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?

>Solution :

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.

Leave a Reply