メインコンテンツへスキップ
Lesson3 / 5

論理演算子 - 条件を組み合わせる

目次

このレッスンで学ぶこと

  • 論理演算子とは何か
  • and、or、notの使い方
  • 複数の条件を組み合わせる方法
  • 論理演算子の優先順位と短絡評価

論理演算子とは

論理演算子は、複数の条件を組み合わせて判定するための演算子です。True(真)とFalse(偽)を操作します。

Pythonの論理演算子一覧

演算子名前意味結果
and論理積両方とも真なら真True and TrueTrue
or論理和どちらか一方が真なら真True or FalseTrue
not論理否定真偽を反転not TrueFalse

論理演算子の特徴

  • 複数の条件を1つにまとめられる
  • if文で複雑な条件判定ができる
  • ブール値(TrueとFalse)を扱う
  • 優先順位: not > and > or

簡単な例

Python
# 基本的な使い方
print(True and True)   # True(両方とも真)
print(True or False)   # True(片方が真)
print(not True)        # False(反転)

# 条件の組み合わせ
age = 20
has_license = True
print(age >= 18 and has_license)  # True(両方の条件を満たす)

なぜ論理演算子が必要なのか?

プログラムでは、複数の条件を同時にチェックする必要があることがよくあります。

Python
age = 25
has_license = True

# 18歳以上かつ免許を持っている
if age >= 18 and has_license:
    print("運転できます")

論理演算子を使うことで、複数の条件を組み合わせて複雑な判定ができます。

💡 豆知識: 論理演算子は、19世紀のイギリスの数学者ジョージ・ブールが考案したブール代数に基づいています。コンピュータの基礎となる重要な概念です。


基本的な論理演算子

and - かつ(論理積)

機能: 両方の条件が真の場合のみ、結果が真になります。

Python
# 基本的な使い方
print(True and True)    # True
print(True and False)   # False
print(False and True)   # False
print(False and False)  # False

# 実用例: 年齢と免許のチェック
age = 20
has_license = True

can_drive = age >= 18 and has_license
print(can_drive)  # True

# 範囲チェック
score = 85
if score >= 0 and score <= 100:
    print("有効な点数")

真理値表:

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

用途: 複数条件の同時満たし、範囲チェック


or - または(論理和)

機能: どちらか一方でも真なら、結果が真になります。

Python
# 基本的な使い方
print(True or True)    # True
print(True or False)   # True
print(False or True)   # True
print(False or False)  # False

# 実用例: 休日判定
is_saturday = True
is_sunday = False

is_weekend = is_saturday or is_sunday
print(is_weekend)  # True

# エラーチェック
error1 = False
error2 = True

has_error = error1 or error2
if has_error:
    print("エラーが発生しました")

真理値表:

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

用途: 複数条件のいずれか満たし、フラグチェック


not - 否定(論理否定)

機能: 真偽値を反転します。

Python
# 基本的な使い方
print(not True)   # False
print(not False)  # True

# 実用例: 反対条件
is_raining = False
can_go_out = not is_raining
print(can_go_out)  # True

# ログイン状態
is_logged_in = False
if not is_logged_in:
    print("ログインしてください")

# 空チェック
text = ""
if not text:
    print("テキストが空です")

真理値表:

Anot A
TrueFalse
FalseTrue

用途: 条件の反転、否定判定


論理演算子の組み合わせ

複数条件の組み合わせ

Python
# and と or の組み合わせ
age = 25
has_license = True
has_car = False

# 18歳以上で、免許または車を持っている
if age >= 18 and (has_license or has_car):
    print("条件を満たしています")

# 括弧で優先順位を明示
score = 85
attendance = 0.9

# 点数60以上かつ出席率80%以上
is_pass = score >= 60 and attendance >= 0.8
print(is_pass)  # True

優先順位

Python
# not > and > or の順
result = True or False and False
print(result)  # True(False and False が先、True or False)

# 括弧で明示的に
result = True or (False and False)
print(result)  # True(同じ)

result = (True or False) and False
print(result)  # False(優先順位が変わる)

優先順位(高い順):

  1. not
  2. and
  3. or

推奨: 括弧を使って明示的にする


短絡評価

andの短絡評価

機能: 左側が偽なら、右側を評価せずに偽を返します。

Python
# 左側がFalseなら右側は評価されない
def check():
    print("check()が呼ばれました")
    return True

result = False and check()
print(result)  # False(check()は呼ばれない)

# 左側がTrueなら右側も評価される
result = True and check()
# 出力: check()が呼ばれました
print(result)  # True

用途: 安全なチェック、パフォーマンス最適化


orの短絡評価

機能: 左側が真なら、右側を評価せずに真を返します。

Python
# 左側がTrueなら右側は評価されない
def check():
    print("check()が呼ばれました")
    return False

result = True or check()
print(result)  # True(check()は呼ばれない)

# 左側がFalseなら右側も評価される
result = False or check()
# 出力: check()が呼ばれました
print(result)  # False

具体例

例1: ログインチェック

Python
username = "admin"
password = "pass123"

# 正しい認証情報
correct_user = "admin"
correct_pass = "pass123"

# 両方正しいかチェック
is_authenticated = username == correct_user and password == correct_pass

if is_authenticated:
    print("ログイン成功")
else:
    print("ユーザー名またはパスワードが違います")

例2: 営業日判定

Python
day = "土曜日"
is_holiday = False

# 土日または祝日なら休み
is_closed = day == "土曜日" or day == "日曜日" or is_holiday

if is_closed:
    print("休業日です")
else:
    print("営業中です")

例3: 割引判定

Python
age = 15
is_student = True
is_senior = False

# 18歳未満、学生、または65歳以上なら割引
gets_discount = age < 18 or is_student or is_senior

if gets_discount:
    print("割引が適用されます")

# より詳細な判定
if age < 18:
    print("子供割引: 50%OFF")
elif is_student:
    print("学生割引: 30%OFF")
elif age >= 65:
    print("シニア割引: 40%OFF")

例4: 入力検証

Python
username = "user123"
password = "MyPass456"

# ユーザー名: 5文字以上
# パスワード: 8文字以上
is_valid_user = len(username) >= 5
is_valid_pass = len(password) >= 8

if is_valid_user and is_valid_pass:
    print("登録できます")
else:
    if not is_valid_user:
        print("ユーザー名は5文字以上にしてください")
    if not is_valid_pass:
        print("パスワードは8文字以上にしてください")

例5: 気温と天気による判定

Python
temperature = 28
is_sunny = True
is_raining = False

# 25度以上で晴れ、かつ雨でない
good_for_outdoor = temperature >= 25 and is_sunny and not is_raining

if good_for_outdoor:
    print("アウトドアに最適です")
else:
    print("屋内活動をおすすめします")

例6: 複雑な条件判定

Python
score = 75
attendance = 0.85
submitted_report = True

# 合格条件:
# - 点数60以上
# - 出席率80%以上
# - レポート提出済み
is_pass = (score >= 60 and
           attendance >= 0.8 and
           submitted_report)

if is_pass:
    print("合格")
else:
    print("不合格")

    # 詳細な理由
    if score < 60:
        print("  理由: 点数不足")
    if attendance < 0.8:
        print("  理由: 出席率不足")
    if not submitted_report:
        print("  理由: レポート未提出")

よくある間違い

間違い1: 複数値の比較

Python
x = 5

# 間違い: このように書けない
if x == 3 or 5 or 7:  # 常にTrue
    print("3, 5, 7のいずれか")

# 正しい
if x == 3 or x == 5 or x == 7:
    print("3, 5, 7のいずれか")

# またはinを使う
if x in [3, 5, 7]:
    print("3, 5, 7のいずれか")

間違い2: andとorの混同

Python
age = 25
has_license = False

# 間違い: orを使ってしまう
if age >= 18 or has_license:  # どちらか一方でTrue
    print("運転できます")  # 免許がなくても表示される

# 正しい: andを使う
if age >= 18 and has_license:
    print("運転できます")

間違い3: 優先順位の誤解

Python
# 問題のある例
result = True or False and False
print(result)  # True(期待: False?)

# and が先に評価される
# True or (False and False)
# True or False
# True

# 括弧で明示
result = (True or False) and False
print(result)  # False

間違い4: notの位置

Python
x = 5

# 間違い
if not x == 5:  # わかりにくい
    print("5ではない")

# 正しい(読みやすい)
if x != 5:
    print("5ではない")

# notを使う場合は括弧で
if not (x == 5):
    print("5ではない")

間違い5: 空の判定

Python
text = ""

# 冗長
if text == "":
    print("空です")

# シンプル(推奨)
if not text:
    print("空です")

# リストの場合も同様
items = []
if not items:
    print("リストが空です")

練習問題

問題1(基礎)⭐☆☆

年齢が18歳以上かつ20歳未満の場合に「高校生または大学生」と表示してください。

💡 ヒント

and を使って2つの条件を組み合わせます。

✅ 解答例
Python
age = 19

if age >= 18 and age < 20:
    print("高校生または大学生")

# チェーン比較でも書ける
if 18 <= age < 20:
    print("高校生または大学生")

実行結果:

高校生または大学生
高校生または大学生

解説: and で両方の条件が真の場合のみ実行されます。


問題2(基礎)⭐☆☆

土曜日または日曜日なら「休日です」と表示してください。

💡 ヒント

or を使います。

✅ 解答例
Python
day = "土曜日"

if day == "土曜日" or day == "日曜日":
    print("休日です")

# inを使った方法
if day in ["土曜日", "日曜日"]:
    print("休日です")

実行結果:

休日です
休日です

解説: or はどちらか一方が真なら真を返します。


問題3(応用)⭐⭐☆

以下の条件で映画館の料金を判定してください:

  • 12歳以下または65歳以上: 800円
  • それ以外: 1800円
💡 ヒント

or で年齢条件を組み合わせます。

✅ 解答例
Python
age = 10

if age <= 12 or age >= 65:
    price = 800
    print(f"{age}歳: {price}円(割引料金)")
else:
    price = 1800
    print(f"{age}歳: {price}円(通常料金)")

実行結果:

10歳: 800円(割引料金)

解説: or で子供料金とシニア料金の両方の条件をチェックしています。


まとめ

このレッスンでは、論理演算子で条件を組み合わせる方法を学びました。

  • and, or, not を使って、複数条件を一つの式として表現できます。
  • 優先順位(not > and > or)を理解すると、判定ミスを防げます。
  • 条件が長い場合は括弧を使って意図を明確に書くことが重要です。
  • 短絡評価の仕組みを理解すると、効率的で安全な条件式を書けます。
  • よくある誤記(例: x == 3 or 5)を避け、比較式を明示的に書く習慣が必要です。