Of course it does – the closest if
with matching indentation, which is how Python
compiles. It wouldn’t make sense in your example:
if x < y:
print(f'{x} is less than {y}.')
if x > y:
print(f'{x} is greater than {y}.')
else:
print(f'{x} is equal to {y}.')
for the else
to reference x<y
, from a readers point of view. It would be the same in any language (with braces). Closest to what you mean but wouldn’t make sense for your example:
if something:
print("something")
if otherThing:
print("that")
else: print("otherwise!")
Now it’s clear the else
belongs to the first if
. This is not Python specific at all. If you want a triple check:
if x > y:
...
elif x < y:
...
else:
...
if (else if) else
construct – that’s the way all languages handle this, not just Python. This is the same as:
if x > y:
...
else:
if x < y:
...
else:
...
which makes clear where each else
belongs.
solved `else` branch only pair to its nearest ‘if’