1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの便利技と注意点:繰り返し編

Last updated at Posted at 2024-04-30

目次に戻る

whileループの抜け出し方

普段for文を常用していると、whileを使いたい時に抜け出す方法を忘れてしまうので備忘録

while文を抜けだすのは、条件となる変数をwhileの前、条件をwhileの中に書く
# 条件となる変数宣言
i = 0

while True:
    i += 1
    print(i)

    # 条件設定
    if i == 3:
        break
出力結果
1
2
3

elseとの組み合わせ

繰り返しを最後まで完了するとelseを実行する
for_list = list(range(1, 5))
print(for_list)

for i in for_list:
    print(i)
else:
    print("finish")
出力結果
[1, 2, 3, 4]
1
2
3
4
finish
最後まで完了せずにbreakするとelseの中は実行されない
for_list = list(range(1, 5))
print(for_list)

for i in for_list:
    if i == 3:
        break
    print(i)
else:
    print("finish")
出力結果
[1, 2, 3, 4]
1
2
whileもforと同様、繰り返しを最後まで完了するとelseを実行する
while_list = list(range(1, 5))
print(while_list)

cnt = 0

while cnt < len(while_list):
    print(while_list[cnt])
    cnt += 1
else:
    print("finish")
出力結果
[1, 2, 3, 4]
1
2
3
4
finish
whileも最後まで完了せずにbreakするとelseの中は実行されない
while_list = list(range(1, 5))
print(while_list)

cnt = 0

while cnt < len(while_list):
    if cnt == 3:
        break
    print(while_list[cnt])
    cnt += 1
else:
    print("finish")
出力結果
[1, 2, 3, 4]
1
2
3

enumerate関数でインデックスも一緒にとってくる

enumerate関数を使わない場合
i = 0
for drink in ['cola', 'green tea', 'water', 'orange juice']:
    print(i, drink)
    i += 1
enumerate関数を使うと2行減らせる
for i, drink in enumerate(['cola', 'green tea', 'water', 'orange juice']):
    print(i, drink)
出力結果
0 cola
1 green tea
2 water
3 orange juice

zip関数で複数要素をまとめて取り出す

zip関数を使わない場合
week_days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
main_dish = ['Ramen', 'Hamburger', 'Curry', 'Beef', 'Chicken']
drink_menu = ['Woolong tea', 'Cola', 'Water', 'Green tea', 'Coffee']

for i in range(len(week_days)):
    print(week_days[i], ':', main_dish[i], ':', drink_menu[i])
zip関数を使う場合
week_days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
main_dish = ['Ramen', 'Hamburger', 'Curry', 'Beef', 'Chicken']
drink_menu = ['Woolong tea', 'Cola', 'Water', 'Green tea', 'Coffee']

for day, main, drink in zip(week_days, main_dish, drink_menu):
    print(day, ':', main, ':', drink)
出力結果
Mon : Ramen : Woolong tea
Tue : Hamburger : Cola
Wed : Curry : Water
Thu : Beef : Green tea
Fri : Chicken : Coffee

掛け算九九で格段を下展開する技

for i in range(1, 10):
    k = ""
    for j in range(1, 10):
        # iとjを逆にすることで、各段をした展開可能
        k = k + "{}x{}={:2d}  ".format(j, i, i*j)
    print(k)
======================================================================
1x1= 1  2x1= 2  3x1= 3  4x1= 4  5x1= 5  6x1= 6  7x1= 7  8x1= 8  9x1= 9  
1x2= 2  2x2= 4  3x2= 6  4x2= 8  5x2=10  6x2=12  7x2=14  8x2=16  9x2=18  
1x3= 3  2x3= 6  3x3= 9  4x3=12  5x3=15  6x3=18  7x3=21  8x3=24  9x3=27  
1x4= 4  2x4= 8  3x4=12  4x4=16  5x4=20  6x4=24  7x4=28  8x4=32  9x4=36  
1x5= 5  2x5=10  3x5=15  4x5=20  5x5=25  6x5=30  7x5=35  8x5=40  9x5=45  
1x6= 6  2x6=12  3x6=18  4x6=24  5x6=30  6x6=36  7x6=42  8x6=48  9x6=54  
1x7= 7  2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49  8x7=56  9x7=63  
1x8= 8  2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64  9x8=72  
1x9= 9  2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81  

階乗を求める

ポイントは0になった時に1を返す再帰処理を行う
def fact(n):
    if n == 0:
        return 1
    return n * fact(n-1)

# ここでは6の階乗を実行した
for num in range(6):
    print(str(num) + "!: " + str(fact(num)))
============================================
0!: 1
1!: 1
2!: 2
3!: 6
4!: 24
5!: 120

目次に戻る

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?