[Tutor] confusion with else command
Peter Otten
__peter__ at web.de
Tue Feb 7 20:08:16 CET 2012
Debashish Saha wrote:
> for i in range(1, 8):
> print(i)
> if i==3:
> break
> else:
> print('The for loop is over')
> Output:
> 1
> 2
> 3
>
> Question:
>
> but after breaking the for loop why the else loop could not work?
The else suite is not invoked because that's the way Guido intended it ;)
It was designed for sitiuations like the following:
for beast in animals:
if is_it_a_cat(beast):
print("There's a cat among those animals")
break
else:
print("Sorry, there aren't any cats")
print("I've been looking for a cat") # you don't need an else for that
i. e. it's only invoked if the loop terminates normally (no break, and of
course no return or exception).
More information about the Tutor
mailing list