While ループ

開発者のためのPython入門

Jasmin Ludolf

Senior Data Science Content Developer

if文

if文

Flow of an if statement: start > condition met > perform action > exit

開発者のためのPython入門

if文 vs. whileループ

if文

Flow of an if statement: start > condition met > perform action > exit

Whileループ

Flow of a while loop: start > condition met > perform action > loop > repeat until condition is no longer met

開発者のためのPython入門

Whileループ

while condition:
    action
  • 任意の連続タスク
    • ボタンが押されている間(while)は加速する

Games console with a racing game

1 https://unsplash.com/@joaoscferrao
開発者のためのPython入門

Whileループ

ingredients_to_add = 5
items_added = 0
# Keep adding while we have items left
while items_added < ingredients_to_add:

items_added += 1 remaining = ingredients_to_add - items_added print(remaining, "ingredients left to add")
開発者のためのPython入門

出力

4 ingredients left to add
3 ingredients left to add
2 ingredients left to add
1 ingredients left to add
0 ingredients left to add
  • items_addedingredients_to_addに等しくなるとループは終了する
開発者のためのPython入門

注意事項

  • 条件が満たされている間、while は継続的に実行される
ingredients_to_add = 5
items_added = 0

while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")
開発者のためのPython入門

永遠に実行される

ingredients_to_add = 5
items_added = 0

# INFINITE LOOP - never exits!
while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")
    # Forgot to increment items_added!
  • 条件は決して偽にならない
  • ループが永遠に実行され、プログラムがフリーズする
  • 開発上のよくあるミス
開発者のためのPython入門

ループの中断

while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")

# Terminate the loop break
  • breakfor ループでも使用可能

  • すでにコードが実行中の場合: Control + C / Command + C

開発者のためのPython入門

while ループ内の条件文

ingredients_to_add = 5
items_added = 0


while items_added < ingredients_to_add: items_added += 1 remaining = ingredients_to_add - items_added
if remaining > 3: print("Several ingredients remaining")
elif remaining >= 1: print("Almost done!")
else: print("Shopping list complete!")
開発者のためのPython入門

条件文の出力

Several ingredients remaining
Several ingredients remaining
Almost done!
Almost done!
Shopping list complete!
開発者のためのPython入門

練習してみましょう!

開発者のためのPython入門

Preparing Video For Download...