0
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?

②if/forの考え方を日常生活のイベントに当てはめてみた!

0
Posted at

🌱Introduction

前回に引き続き、今度はif / forの考え方を書いていきます。
これも書くことで、ifforの順番が異なることでどうなるのかの比較を載せたいと思います。

🍱 ①「お腹が空いたら、冷蔵庫の中を順番に見る」

if(お腹が空いたら)
→ for(冷蔵庫の中の食材を順番に見る)

lunch_box.py
if hungry:
    for item in fridge:
        print(item)

🛒 ②「雨が降っていたら、買い物リストを順番に確認して傘を持つ」

if(雨が降っている)
→ for(買い物リストを順番にチェック)

shopping.py
if is_raining:
    for thing in shopping_list:
        print("Check:", thing)

📱 ③「通知が来ていたら、通知を順番に読む」

if(通知がある)
→ for(通知を1つずつ読む)

notification.py
if notifications:
    for n in notifications:
        print(n)

🧹 ④「部屋が汚れていたら、各エリアを順番に掃除する」

if(部屋が汚い)
→ for(エリアを順番に掃除)

room.py
if room.is_dirty():
    for area in room.areas:
        clean(area)

🚉 ⑤「電車が遅延していたら、各駅の状況を順番に確認する」

if(遅延している)
→ for(駅を順番にチェック)

train.py
if train.is_delayed():
    for station in line:
        check_status(station)

🧩 プログラム的にはどういう時に使う?

✔ 条件が成立した時だけループを実行したい時

例:n が 5 以下ならループを開始

number.py
if n <= 5:
    for i in range(10):
        print(i)

✔ ループを “条件付きで有効化” したい時

例:ログインしている時だけ処理する

login.py
if user.is_logged_in():
    for msg in messages:
        print(msg)

✔ エラーが起きた時だけリトライする

例:エラーが起きたら 3 回再試行

error_retry.py
if error:
    for retry in range(3):
        try_again()

✔ 特定の状態の時だけ繰り返し処理をする

例:ゲームが開始状態ならターン処理をする

game_start.py
if game.started:
    for turn in range(100):
        play_turn()

🧠 まとめ:“if の中に for” の意味

条件が成立した時だけ、繰り返し処理をする

逆に言うと:

  • 条件が成立しなければ、ループはそもそも始まらない

  • 条件が成立したら、ループが動き始める

これは日常の行動そのもの。

0
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
0
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?