CodeAddicted CodeAddicted - 2 months ago 7
Python Question

If/else proper indentation inside while loop

I started learning programming with Python about a few weeks now
and I am having some trouble.
The following code is a tiny program that checks whether there's an even number in a list, if it finds the first even number, it breaks out of the loop:

numbers = [1, 3, 5]
position = 0

while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
position += 1

else: # break not called
print('No even number found')


That prints the error:

File "test.py", line 11
else: # break not called
^
SyntaxError: invalid syntax


That's an indentation issue, if I remove the tab before "else" and so align it with 'while' the program runs really well:

while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
position += 1

else:
print('No even number found')

# Prints: No even number found


My question is, why does 'else' needs to be aligned with 'while' instead of being aligned with 'if' inside the loop?

That's all I want to know guys!
Thanx in advance!

Answer

When you remove the indent you are using a while:else block. The else is being attached to while which means it will run if your while condition is false.

while True:
    ##some looping code
else:
    ##code to run when while is false

When you indent that line of code you attach the else to if making an if:else block. In this case else is executed when if is false.

if True:
    ##code to run if true
else
    ##code to run if false

Blocks of code in python follow the same indentation. Because "else" is part of the "while" block, it has to be at the same tab position for it to work, and looking at your code, I'd say the while:else block is what you intended. :)