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!
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. :)
Try like this:
numbers = [1, 3, 5]
position = 0
while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
else: # break not called
print('No even number found')
position += 1
Here is the problem. There are two types of else
statements in this case. If you align the else
statement with while
, the else
statement is executed when the condition of the while
loop becomes false.
In your code, the else statement gets executed when position < len(numbers)
is not true.
Also, the syntax problem is occurring just because you have a line of code between the if
and else
statements, which is position += 1
If you want to use an else
statement for your if
statement (not for the while
statement as I suggested at the beginning), you should move this line of code in between of if
and else
.
Try this:
while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
else:
print('No even number found')
position += 1
Hope this helps.
来源:https://stackoverflow.com/questions/39651423/if-else-proper-indentation-inside-while-loop