Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading