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/ifの考え方を日常生活のイベントに当てはめてみた!

0
Posted at

🌏 Introduction

ifforif は “条件が成立したらループを開始し、そのループの中でさらに条件判定する” という構造。
日常生活にもめちゃ自然に存在してる。

🍱 ①「雨が降っていたら → 買い物リストを順番に見る → 生ものだけ買う」

日常の流れ
  • 雨が降っていたら(if
  • 買い物リストを順番に見る(for
  • 生ものだけ買う(if
rainy_shopping.py
is_raining = True

shopping_list = [
    {"name": "パン", "fresh": False},
    {"name": "牛肉", "fresh": True},
    {"name": "りんご", "fresh": False},
    {"name": "刺身", "fresh": True},
]

if is_raining:                                   # if(雨なら)
    for item in shopping_list:                   # for(リストを順番に見る)
        if item["fresh"]:                        # if(生ものだけ)
            print(f"買う: {item['name']}")

🧺 ②「部屋が汚れていたら → 各エリアを順番に見る → 汚れてる場所だけ掃除する」

日常の流れ
  • 部屋が汚れていたら(if
  • エリアを順番に見る(for
  • 汚れてる場所だけ掃除(if
room_dirty.py
room_dirty = True

areas = {
    "": False,
    "": True,
    "": False,
    "キッチン": True
}

if room_dirty:                                   # if(部屋が汚い)
    for area, dirty in areas.items():            # for(エリアを順番に見る)
        if dirty:                                 # if(汚れてる場所だけ)
            print(f"掃除する: {area}")

🚉 ③「電車が遅延していたら → 全駅を順番に見る → 混雑してる駅だけアナウンスする」

日常の流れ
  • 遅延していたら(if
  • 全駅を順番に見る(for
  • 混雑してる駅だけアナウンス(if

🎮 ④「ゲーム開始中なら → 敵リストを順番に見る → ボスだけ特別処理する」

日常の流れ
  • ゲームが開始していたら(if
  • 敵を順番に見る(for
  • ボスだけ特別処理(if
game_start.py
game_started = True

enemies = [
    {"name": "スライム", "boss": False},
    {"name": "ゴブリン", "boss": False},
    {"name": "ドラゴン", "boss": True}
]

if game_started:                                  # if(ゲーム開始)
    for enemy in enemies:                          # for(敵を順番に見る)
        if enemy["boss"]:                          # if(ボスだけ)
            print(f"ボス戦開始: {enemy['name']}")

🎯 Conclusion

ifforif は “条件が成立したらループ開始 → ループ中でさらに条件判定” の構造。
日常生活に自然に存在していて、Python に落とすとめちゃ理解しやすい。

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?