while文は条件が真の間、繰り返す制御文です。
# -*- coding: utf-8 -*- # file : whilestatements.py i = 0 # 構文は # while <条件> # suite.... # while i < 10: i += 1 print(i)
[paso ~] python3 whilestatements.py
1
2
3
4
5
6
7
8
9
10
Pythonのfor文はタプル型のようなリスト形式のみ扱います。 他の言語のように変数を初期化しインクリメントする機能はありません。
# -*- coding: utf-8 -*- # file : forstatements.py name_list = 'Eclair', 'Froyo', 'Gingerbread', 'Honeycomb', 'IceCreamSandwich' # 構文は # for <ターゲット> in <リスト>: # suite.... for name in name_list: print (name)
[paso ~] python3 forstatements.py
場合によってはループ内の処理を実行したくない場合は、ループを終了したい時があります。 その時にしようするのが、continue(継続), break(中断)です。
# -*- coding: utf-8 -*- # file : loop_continue.py # # 果物と野菜リスト(name_list)から果物のみを抽出する # # 果物と野菜リスト mixed_list = 'Apple', 'Orange', 'Eggplant', 'Grape', 'Orange', 'Eggplant', 'Grape' # 果物の個数用の変数 furuite_count = 0; for name in mixed_list: # 野菜の場合、ループに戻る if name == 'Eggplant': continue # ここには果物の場合のみくる furuite_count += 1 print(name) print('果物の個数は' + str(furuite_count) + 'です。')
[paso ~] python3 loop_continue.py
Apple
Orange
Grape
Orange
Grape
果物の個数は5です。
# -*- coding: utf-8 -*- # file : loop_break.py # 果物と野菜リスト mixed_list = 'Apple', 'Orange', 'Eggplant', 'Grape', 'Orange', 'Eggplant', 'Grape' # 果物の個数用の変数 furuite_count = 0; for name in mixed_list: # 野菜の場合、ループを抜ける if name == 'Eggplant': break furuite_count += 1 print(name) print('野菜が出てくるまでの果物の個数は' + str(furuite_count) + 'です。')
[paso ~] python3 loop_break.py
Apple
Orange
野菜が出てくるまでの果物の個数は2です。
Pythonはforやwhileにelse文が使用できます。 else文はループが正常に終了すると実行されますが、breakでループを抜けると実行されません。
# -*- coding: utf-8 -*- # file : loop_else.py even_list = (2, 4, 6, 8, 10) for num in even_list: # 2で割ったあまりが1( = 奇数)の場合 if num % 2 == 1: print(str(num) + 'は奇数です。') break else: print('全ての数は偶数です。') # リストの4番目の値を奇数に変更 even_list = (2, 4, 6, 7, 10) for num in even_list: # 2で割ったあまりが1( = 奇数)の場合 if num % 2 == 1: print(str(num) + 'は奇数です。') break else: # breakで抜けるのでこれは実行されません。 print('全ての数は偶数です。')
[paso ~] python3 loop_break.py
全ての数は偶数です。
7は奇数です。
if文同様、pass文が使用できます。
# -*- coding: utf-8 -*- # file : loop_pass.py num_list = (1, 2, 3, 5, 8) for num in num_list: # for文何は1つ上の記述が必要なので、何もしたくない場合はpassを使う pass print('最後の数字は' + str(num) + 'です。')
[paso ~] python3 loop_pass.py
最後の数字は8です。
COPYRIGHT © 2008 Deepnet Inc. ALL RIGHTS RESERVED.