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 文の基本【Day 7】

0
Last updated at Posted at 2025-12-06

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

条件分岐 if 文の基本

Python の条件分岐は「もし〜なら〜する」を書くための仕組みです。
プログラミングの基礎中の基礎なので、ここでしっかり押さえましょう。

if 文の基本形

if 条件式:
    処理

age = 20

if age >= 18:
    print("成人です")

ポイント

  • :(コロン)を忘れない
  • インデント(字下げ)は半角スペース4つが基本
  • 条件が True なら処理が実行される

条件式の例

x == 10   # xが10と等しい
x != 10   # xが10でない
x > 5     # xが5より大きい
x <= 3    # xが3以下

ブール値(True/False)になる式なら何でもOKです。

比較と組み合わせ

and(かつ)

if score >= 70 and score <= 100:
    print("合格")

or(または)

if day == "" or day == "":
    print("休日")

実用的な例

temperature = 30

if temperature > 25:
    print("暑いですね")

よくあるエラー

1. : を忘れる

if x > 5   # NG

2. インデントが不揃い

if x > 5:
  print("OK")    # 2スペース
    print("NG")  # 4スペース → エラーの原因

まとめ

  • if 文は「条件が True なら実行」する仕組み
  • : とインデントが必須
  • 条件式は True / False を返す式なら何でもOK
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?