【Python入門】True/Falseを初心者向けに完全解説!真偽値と条件分岐の使い方

PythonにおけるTrue/False(真偽値・ブール値)は、プログラミングの基礎となる重要な概念です。条件分岐やループ処理で頻繁に使用され、プログラムの論理的な判断を担っています。この記事では、True/Falseの基本から実践的な使い方まで、初心者の方にも分かりやすく解説します。

True/False(真偽値)とは?

True/Falseは、Pythonにおける真偽値(ブール値)を表すキーワードです。プログラムが「はい」か「いいえ」の判断をする際に使用されます。

基本概念

  • True: 真(正しい、条件が満たされている)
  • False: 偽(間違い、条件が満たされていない)
  • bool型: Pythonの真偽値データ型

基本的なTrue/Falseの使い方

1. 真偽値の代入と表示

is_sunny = True
is_raining = False

print(is_sunny)   # True
print(is_raining) # False
print(type(is_sunny))  # <class 'bool'>

2. 比較演算子とTrue/False

age = 20
print(age >= 18)  # True(20は18以上)
print(age < 18)   # False(20は18未満ではない)

name = "田中"
print(name == "田中")  # True
print(name == "佐藤")  # False

3. 条件分岐での使用

is_student = True

if is_student:
    print("学生です")
else:
    print("学生ではありません")
# 学生です

比較演算子によるTrue/False

数値の比較

a = 10
b = 5

print(a > b)   # True(10は5より大きい)
print(a < b)   # False(10は5より小さくない)
print(a == b)  # False(10と5は等しくない)
print(a != b)  # True(10と5は等しくない)
print(a >= 10) # True(10は10以上)
print(a <= 9)  # False(10は9以下ではない)

文字列の比較

name1 = "山田"
name2 = "田中"

print(name1 == name2)  # False
print(name1 != name2)  # True
print("a" < "b")       # True(辞書順)
print("abc" == "abc")  # True

論理演算子(and, or, not)

1. and演算子(かつ)

age = 25
has_license = True

# 両方の条件がTrueの場合のみTrue
can_drive = age >= 18 and has_license
print(can_drive)  # True

# 一方がFalseの場合はFalse
age = 16
can_drive = age >= 18 and has_license
print(can_drive)  # False

2. or演算子(または)

is_weekend = True
is_holiday = False

# どちらか一方がTrueならTrue
can_relax = is_weekend or is_holiday
print(can_relax)  # True

# 両方がFalseの場合のみFalse
is_weekend = False
can_relax = is_weekend or is_holiday
print(can_relax)  # False

3. not演算子(否定)

is_busy = True
is_free = not is_busy
print(is_free)  # False

is_working = False
is_available = not is_working
print(is_available)  # True

4. 複合条件

age = 25
has_license = True
has_car = False

# 複数の論理演算子を組み合わせ
can_drive_today = age >= 18 and has_license and (has_car or True)
print(can_drive_today)  # True

Truthyな値とFalsyな値

Falsyな値(Falseとして扱われる)

# 以下の値は条件判定でFalseとして扱われる
falsy_values = [
    False,      # ブール値のFalse
    0,          # 数値の0
    0.0,        # 浮動小数点の0.0
    "",         # 空文字列
    [],         # 空のリスト
    {},         # 空の辞書
    set(),      # 空のセット
    None        # None値
]

for value in falsy_values:
    if value:
        print(f"{value} はTruthy")
    else:
        print(f"{value} はFalsy")

Truthyな値(Trueとして扱われる)

# 以下の値は条件判定でTrueとして扱われる
truthy_values = [
    True,       # ブール値のTrue
    1,          # 0以外の数値
    -1,         # 負の数値
    "hello",    # 空でない文字列
    [1, 2, 3],  # 空でないリスト
    {"key": "value"},  # 空でない辞書
]

for value in truthy_values:
    if value:
        print(f"{value} はTruthy")
    else:
        print(f"{value} はFalsy")

実践的なTrue/Falseの活用例

1. ユーザー認証システム

def authenticate_user(username, password):
    # 簡単な認証例
    correct_username = "admin"
    correct_password = "password123"
    
    is_username_correct = username == correct_username
    is_password_correct = password == correct_password
    
    return is_username_correct and is_password_correct

# 使用例
result = authenticate_user("admin", "password123")
if result:
    print("ログイン成功")
else:
    print("ログイン失敗")

2. 成績判定システム

def evaluate_student(score, attendance_rate):
    passed_exam = score >= 60
    good_attendance = attendance_rate >= 0.8
    
    if passed_exam and good_attendance:
        return "合格"
    elif passed_exam and not good_attendance:
        return "出席不足で不合格"
    else:
        return "試験不合格"

result = evaluate_student(75, 0.9)
print(result)  # 合格

3. 商品在庫チェック

class Product:
    def __init__(self, name, stock, price):
        self.name = name
        self.stock = stock
        self.price = price
        self.is_available = stock > 0
    
    def can_purchase(self, quantity, budget):
        has_enough_stock = self.stock >= quantity
        has_enough_money = budget >= (self.price * quantity)
        
        return self.is_available and has_enough_stock and has_enough_money

product = Product("ノートPC", 5, 80000)
can_buy = product.can_purchase(2, 200000)
print(can_buy)  # True

4. フォームバリデーション

def validate_registration_form(email, password, age):
    # メールアドレスの簡単なチェック
    valid_email = "@" in email and "." in email
    
    # パスワードの強度チェック
    strong_password = len(password) >= 8 and any(c.isupper() for c in password)
    
    # 年齢チェック
    valid_age = 18 <= age <= 100
    
    return {
        "is_valid": valid_email and strong_password and valid_age,
        "email_valid": valid_email,
        "password_strong": strong_password,
        "age_valid": valid_age
    }

result = validate_registration_form("user@example.com", "Password123", 25)
print(result)
# {'is_valid': True, 'email_valid': True, 'password_strong': True, 'age_valid': True}

in演算子とTrue/False

リストや文字列での検索

fruits = ["りんご", "バナナ", "オレンジ"]

# in演算子は真偽値を返す
has_apple = "りんご" in fruits
has_grape = "ぶどう" in fruits

print(has_apple)  # True
print(has_grape)  # False

# 文字列での検索
text = "Python プログラミング"
contains_python = "Python" in text
print(contains_python)  # True

辞書での検索

user_data = {
    "name": "田中",
    "age": 30,
    "city": "東京"
}

has_name = "name" in user_data
has_email = "email" in user_data

print(has_name)   # True
print(has_email)  # False

is演算子とTrue/False

オブジェクトの同一性チェック

a = True
b = True
c = 1

print(a is b)      # True(同じオブジェクト)
print(a is c)      # False(異なる型)
print(a == c)      # True(値は等しい)

# None値のチェック
value = None
print(value is None)     # True
print(value is not None) # False

条件式(三項演算子)

簡潔な条件分岐

age = 20
status = "成人" if age >= 18 else "未成年"
print(status)  # 成人

score = 85
grade = "合格" if score >= 60 else "不合格"
print(grade)  # 合格

# 複数の条件
weather = "晴れ"
activity = "外出" if weather == "晴れ" else "室内"
print(activity)  # 外出

bool()関数による変換

値を真偽値に変換

# 数値の変換
print(bool(1))    # True
print(bool(0))    # False
print(bool(-5))   # True

# 文字列の変換
print(bool("hello"))  # True
print(bool(""))       # False

# リストの変換
print(bool([1, 2, 3]))  # True
print(bool([]))         # False

# カスタム関数での使用
def is_positive(number):
    return bool(number > 0)

print(is_positive(5))   # True
print(is_positive(-3))  # False

よくある間違いと注意点

1. 代入と比較の混同

# ❌ 間違い - 代入演算子
# if age = 18:  # SyntaxError

# ✅ 正解 - 比較演算子
age = 18
if age == 18:
    print("18歳です")

2. is と == の使い分け

# ❌ 間違い - 値の比較にisを使用
# if name is "田中":  # 動作するが推奨されない

# ✅ 正解 - 値の比較には==を使用
name = "田中"
if name == "田中":
    print("田中さんです")

# isはNoneや真偽値の比較に使用
value = None
if value is None:
    print("値がありません")

3. 真偽値の直接比較

# ❌ 冗長な書き方
is_student = True
if is_student == True:
    print("学生です")

# ✅ 簡潔な書き方
if is_student:
    print("学生です")

# ❌ 冗長な書き方
if is_student != False:
    print("学生です")

# ✅ 簡潔な書き方
if is_student:
    print("学生です")

True/Falseのベストプラクティス

1. 意味のある変数名を使用

# ✅ 良い例
is_logged_in = True
has_permission = False
can_edit = True

# ❌ 悪い例
flag1 = True
status = False
check = True

2. 関数の戻り値として活用

def is_even(number):
    """数値が偶数かどうかを判定"""
    return number % 2 == 0

def has_valid_email(email):
    """有効なメールアドレスかどうかを判定"""
    return "@" in email and "." in email

print(is_even(4))  # True
print(has_valid_email("user@example.com"))  # True

3. 早期リターンパターン

def process_user(user):
    # 早期リターンで条件をチェック
    if not user:
        return False
    
    if not user.get("email"):
        return False
    
    if user.get("age", 0) < 18:
        return False
    
    # 全ての条件をクリアした場合の処理
    return True

まとめ

PythonのTrue/Falseは、プログラムの論理的な判断を行う上で欠かせない重要な概念です。条件分岐やループ処理、関数の戻り値など、様々な場面で活用されています。

重要なポイント

  • True/Falseは真偽値を表すキーワード
  • 比較演算子と論理演算子で複雑な条件を作成
  • TruthyとFalsyの概念を理解する
  • is と == の使い分けに注意
  • 意味のある変数名で可読性を向上

まずは簡単な条件分岐から始めて、徐々に複雑な論理判断を扱えるようになりましょう。実際にコードを書いて練習することで、True/Falseの使い方がしっかりと身に付きます!

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座