Python 入門 ノート (33)for else

for else文

for fruit in ['apple', 'banana', 'orange']:
    print((fruit))

apple
banana
orange

else

for fruit in ['apple', 'banana', 'orange']:
    print((fruit))
else:
    print('I ate all!')

apple
banana
orange
I ate all!

break 以降はelse文は実行されません

for fruit in ['apple', 'banana', 'orange']:
    if fruit == 'banana':
        print('stop eating')
        break
    print((fruit))
else:
    print('I ate all!')

apple
stop eating

コメント