jeudi 22 septembre 2016

If/Else proper indentation inside While loop in Python

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!

Aucun commentaire:

Enregistrer un commentaire