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?

if-elif-else を図で理解する【Day 8】

1
Last updated at Posted at 2025-12-07

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day8 の記事です。

if-elif-else を図で理解する

昨日の if 文に続き、今日は複数の条件を順番に判断できる if-elif-else を図付きで理解します。

if-elif-else の基本形

if 条件A:
    処理A
elif 条件B:
    処理B
else:
    処理C

実行されるのは 最初に True になった1つだけ です。

図で理解する

                +---- YES ----> 処理A
                |
スタート ----> 判定A
                |
                +---- NO  ----> 判定B ---- YES ----> 処理B
                                  |
                                  +---- NO ----> 処理C(どれも当てはまらない)

具体例:点数による評価

score = 75

if score >= 90:
    print("A評価")
elif score >= 70:
    print("B評価")
else:
    print("C評価")

上から順に評価され、

  • 90点以上なら「A」
  • それ以外で 70点以上なら「B」
  • どちらでもなければ「C」

となります。

elif はいくつでも使える

time = 15

if time < 12:
    print("午前")
elif time < 18:
    print("午後")
elif time < 22:
    print("夜")
else:
    print("深夜")

よくある間違い

条件を重ね書きしてしまう

if score >= 70:
    print("OK")
elif score >= 90:   # ここは絶対に実行されない
    print("Great!")

「70以上」が True の時点で print("OK") が実行され、止まるため、90以上でも最初の if のみが実行され、 print("Great!") はいかなる場合でも実行されません。

まとめ

  • if → elif → else の順に評価される
  • True になった最初の処理だけ実行される
  • elif は何個でもOK
  • 条件の順番が大切
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?