
This is one of the most common errors for beginners, and it’s almost always an IndentationError in disguise. The SyntaxError invalid syntax else issue is especially confusing for new Python programmers.
Python is complaining because your else or elif is in the wrong place.
The Rule
An else or elif statement must be at the exact same indentation level as its if statement, and it must come immediately after the if block.
Cause 1: Wrong Indentation Level
Your else is indented inside the if block, which is not allowed.
Problem Code:
x = 10
if x > 5:
print("x is greater than 5")
else: # CRASH!
print("x is 5 or less")Python sees the else indented under the if and gets confused.
The Fix: Un-indent the else to match the if.
x = 10
if x > 5:
print("x is greater than 5")
else: # Correct!
print("x is 5 or less")Cause 2: Code Between the if and else
You cannot have any code between the end of an if block and its else.
Problem Code:
if x > 5:
print("x is greater than 5")
print("Doing another check...") # This line is the problem
else: # CRASH!
print("x is 5 or less")The else statement feels “orphaned” because it’s not directly attached to the if block anymore.
The Fix: Move any intermediate code to be inside one of the blocks or after the entire if/else statement.
if x > 5:
print("x is greater than 5")
print("Doing another check...") # Correct!
else:
print("x is 5 or less")




