【Python基礎】and, or, notによる条件の組み合わせ方

and, or, not による条件の結合

複数の条件を組み合わせるための演算子です。これにより、ネストを深くすることなく複合条件を書けます。

1. and:両方の条件が真のとき

age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("入場できます")
else:
    print("入場できません")
▶ 出力結果

入場できます

2. or:どちらかの条件が真のとき

is_weekend = False
is_holiday = True

if is_weekend or is_holiday:
    print("今日はお休みです")
else:
    print("平日です")
▶ 出力結果

今日はお休みです

3. not:条件を反転させる

is_empty = False

if not is_empty:
    print("データがあります")

# 範囲外の判定
score = 75
if not (score < 0 or score > 100):
    print(f"有効なスコア:{score}")
▶ 出力結果

データがあります
有効なスコア:75

4. and / or / not の優先順位

# 優先順位:not > and > or
# カッコで明示的にグループ化すると読みやすい
a = True
b = False
c = True

print(a or b and c)        # b and c が先に評価される → True or False → True
print((a or b) and c)      # (True or False) and True → True
▶ 出力結果

True
True
< 前の記事True・False(ブール型)の正体
次の記事 >in演算子(含まれているか?)

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

上部へスクロール