** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
for_else
for fruit in ['apple', 'banana', 'orange']:
print(fruit)
else:
print('I ate all!')
result
apple
banana
orange
I ate all!
As with the while else statement, if you break out of the for
loop without a break
, the one in the ʻelse` is executed.
break
for_else_break
for fruit in ['apple', 'banana', 'orange']:
if fruit == 'banana':
print('stop eating')
break
print(fruit)
else:
print('I ate all!')
result
apple
stop eating
Since break
exited the for
loop, anything in ʻelse` is not executed.
Recommended Posts