【完全ガイド】Pythonの比較演算子一覧と使い方|数値・文字列・オブジェクトの違いも解説

python

プログラミングを学び始めると、必ずと言っていいほど出てくるのが「条件分岐」です。

「この値が大きければAの処理、小さければBの処理をしたい」
「入力された文字列が正しいかどうかチェックしたい」

そんなとき活躍するのが、Pythonの比較演算子です。

比較演算子は、2つの値を比べて「正しい(True)」か「間違い(False)」かを判定するための基本的な仕組みです。

if文やwhile文などの条件式で必須の知識となります。

この記事では、Python初心者の方でも理解できるように:

  • 比較演算子の基本的な種類と使い方
  • 数値、文字列、リストなど異なるデータ型での比較方法
  • よくある間違いと正しい使い方
  • 実際のプログラムで使える実用例

これらを、豊富なサンプルコードと一緒に詳しく解説していきます。

スポンサーリンク

比較演算子とは?|値を比べてTrue/Falseを返す仕組み

比較演算子とは、2つの値を比較して、その結果をTrue(正しい)またはFalse(間違い)で返す演算子のことです。

基本的な動作例

# 基本的な比較
print(5 > 3)      # True(5は3より大きい)
print(10 == 10)   # True(10と10は等しい)
print("A" != "B") # True(AとBは等しくない)

# 結果をif文で使う
age = 20
if age >= 18:
    print("成人です")
else:
    print("未成年です")

実行結果:

True
True
True
成人です

比較演算子の結果は必ずTrue(真)かFalse(偽)のどちらかになり、これをブール値(boolean)と呼びます。

Pythonの比較演算子一覧

基本的な比較演算子

演算子読み方意味使用例結果
==イコール等しい5 == 5True
!=ノットイコール等しくない3 != 5True
>グレーターザンより大きい7 > 4True
<レスザンより小さい2 < 8True
>=グレーターイコール以上(同じかより大きい)5 >= 5True
<=レスイコール以下(同じかより小さい)3 <= 2False

オブジェクト比較演算子

演算子意味使用例
is同じオブジェクトa is b
is not異なるオブジェクトa is not b

実際に試してみよう

# 数値の比較
print("=== 数値の比較 ===")
print(f"10 == 10: {10 == 10}")
print(f"5 != 3: {5 != 3}")
print(f"8 > 6: {8 > 6}")  
print(f"4 < 2: {4 < 2}")
print(f"7 >= 7: {7 >= 7}")
print(f"9 <= 8: {9 <= 8}")

実行結果:

=== 数値の比較 ===
10 == 10: True
5 != 3: True
8 > 6: True
4 < 2: False
7 >= 7: True
9 <= 8: False

データ型別の比較方法

文字列の比較

文字列は辞書順(アルファベット順)で比較されます。

print("=== 文字列の比較 ===")
print(f"'apple' == 'apple': {'apple' == 'apple'}")
print(f"'apple' != 'banana': {'apple' != 'banana'}")

# アルファベット順での大小比較
print(f"'apple' < 'banana': {'apple' < 'banana'}")  # aはbより前
print(f"'cat' > 'dog': {'cat' > 'dog'}")            # cはdより前なのでFalse

# 大文字と小文字は区別される
print(f"'Apple' == 'apple': {'Apple' == 'apple'}")  # 大文字小文字は違う文字

実行結果:

=== 文字列の比較 ===
'apple' == 'apple': True
'apple' != 'banana': True
'apple' < 'banana': True
'cat' > 'dog': False
'Apple' == 'apple': False

重要なポイント:

  • 日本語も比較できますが、文字コード順になります
  • 大文字と小文字は別の文字として扱われます
  • 文字列の長さが違っても比較できます

リストとタプルの比較

リストやタプルは、要素を順番に比較していきます。

print("=== リストの比較 ===")
# 完全一致の比較
print(f"[1, 2, 3] == [1, 2, 3]: {[1, 2, 3] == [1, 2, 3]}")
print(f"[1, 2] != [1, 3]: {[1, 2] != [1, 3]}")

# 大小比較(最初の要素から順番に比較)
print(f"[1, 2] < [1, 3]: {[1, 2] < [1, 3]}")      # 2番目の要素で決まる
print(f"[2, 1] > [1, 9]: {[2, 1] > [1, 9]}")      # 1番目の要素で決まる

# 長さが違うリスト
print(f"[1, 2] < [1, 2, 3]: {[1, 2] < [1, 2, 3]}")  # 短い方が小さい

print("=== タプルの比較 ===")
print(f"(1, 2) == (1, 2): {(1, 2) == (1, 2)}")
print(f"(1, 2) < (2, 1): {(1, 2) < (2, 1)}")

実行結果:

=== リストの比較 ===
[1, 2, 3] == [1, 2, 3]: True
[1, 2] != [1, 3]: True
[1, 2] < [1, 3]: True
[2, 1] > [1, 9]: True
[1, 2] < [1, 2, 3]: True
=== タプルの比較 ===
(1, 2) == (1, 2): True
(1, 2) < (2, 1): True

重要な違い:「==」と「is」の使い分け

初心者が最も混乱しやすいのが、==isの違いです。

演算子比較する内容使用場面
==が同じかどうか一般的な比較
isオブジェクト自体が同じかどうかNoneとの比較など

具体例で理解しよう

print("=== == と is の違い ===")

# 数値の場合
a = 5
b = 5
print(f"a == b: {a == b}")  # 値が同じ
print(f"a is b: {a is b}")  # 小さい整数は同じオブジェクト

# リストの場合
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(f"list1 == list2: {list1 == list2}")  # 値が同じ
print(f"list1 is list2: {list1 is list2}")  # 異なるオブジェクト
print(f"list1 is list3: {list1 is list3}")  # 同じオブジェクト

# Noneとの比較(推奨される書き方)
value = None
print(f"value is None: {value is None}")      # 推奨
print(f"value == None: {value == None}")      # 動作するが推奨されない

実行結果:

=== == と is の違い ===
a == b: True
a is b: True
list1 == list2: True
list1 is list2: False
list1 is list3: True
value is None: True
value == None: True
  • ==:「中身が同じ?」
  • is:「全く同じもの?」

連続比較|Pythonの便利な機能

Pythonでは、比較演算子を連続して書くことができます。

print("=== 連続比較 ===")

# 範囲チェック
x = 15
print(f"10 < x < 20: {10 < x < 20}")  # 10より大きく20より小さい
print(f"0 <= x <= 100: {0 <= x <= 100}")  # 0以上100以下

# 他の言語風の書き方(推奨されない)
print(f"10 < x and x < 20: {10 < x and x < 20}")

# 複数の等値チェック
a, b, c = 5, 5, 5
print(f"a == b == c: {a == b == c}")  # 全て等しい

実行結果:

=== 連続比較 ===
10 < x < 20: True
0 <= x <= 100: True
10 < x and x < 20: True
a == b == c: True

この書き方により、コードがより読みやすくなります。

実用的な使用例

例1:年齢による区分判定

def check_age_category(age):
    """年齢による区分を判定する関数"""
    if age < 0:
        return "無効な年齢です"
    elif age < 13:
        return "子供"
    elif age < 20:
        return "学生"
    elif age < 65:
        return "成人"
    else:
        return "シニア"

# テスト
ages = [5, 15, 25, 70, -1]
for age in ages:
    category = check_age_category(age)
    print(f"年齢{age}歳 → {category}")

実行結果:

年齢5歳 → 子供
年齢15歳 → 学生
年齢25歳 → 成人
年齢70歳 → シニア
年齢-1歳 → 無効な年齢です

例2:成績評価システム

def get_grade(score):
    """点数から成績を判定する関数"""
    if not (0 <= score <= 100):
        return "無効な点数"
    elif score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

# 成績判定のテスト
scores = [95, 85, 75, 65, 55, 105, -10]
for score in scores:
    grade = get_grade(score)
    print(f"{score}点 → {grade}")

実行結果:

95点 → A
85点 → B
75点 → C
65点 → D
55点 → F
105点 → 無効な点数
-10点 → 無効な点数

例3:リストのフィルタリング

# 偶数のみを抽出
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []

for num in numbers:
    if num % 2 == 0:  # 2で割った余りが0(偶数)
        even_numbers.append(num)

print(f"元のリスト: {numbers}")
print(f"偶数のみ: {even_numbers}")

# 文字列の長さでフィルタリング
words = ["cat", "elephant", "dog", "butterfly", "ant"]
long_words = []

for word in words:
    if len(word) >= 5:  # 5文字以上
        long_words.append(word)

print(f"全ての単語: {words}")
print(f"5文字以上: {long_words}")

実行結果:

元のリスト: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
偶数のみ: [2, 4, 6, 8, 10]
全ての単語: ['cat', 'elephant', 'dog', 'butterfly', 'ant']
5文字以上: ['elephant', 'butterfly']

よくある間違いと対処法

間違い1:代入演算子「=」と比較演算子「==」の混同

# 間違った例
x = 5
# if x = 5:  # これは構文エラー!
#     print("xは5です")

# 正しい例
if x == 5:
    print("xは5です")

間違い2:異なる型の比較

# 注意が必要な例
print(f"5 == '5': {5 == '5'}")        # False(数値と文字列)
print(f"True == 1: {True == 1}")      # True(ブール値と数値)
print(f"False == 0: {False == 0}")    # True(ブール値と数値)

# 型を変換してから比較
number = 5
text = "5"
print(f"number == int(text): {number == int(text)}")  # True

実行結果:

5 == '5': False
True == 1: True
False == 0: True
number == int(text): True

間違い3:浮動小数点数の比較

# 浮動小数点の精度問題
result = 0.1 + 0.2
print(f"0.1 + 0.2 = {result}")
print(f"result == 0.3: {result == 0.3}")  # False!

# 正しい比較方法
import math
print(f"math.isclose(result, 0.3): {math.isclose(result, 0.3)}")  # True

実行結果:

0.1 + 0.2 = 0.30000000000000004
result == 0.3: False
math.isclose(result, 0.3): True

論理演算子との組み合わせ

比較演算子は、論理演算子(andornot)と組み合わせて使うことがよくあります。

# 複数条件の組み合わせ
age = 25
income = 300000

# and(かつ)
if age >= 20 and income >= 200000:
    print("ローンの審査に通ります")

# or(または)
if age < 18 or age > 65:
    print("割引対象です")

# not(否定)
password = "abc123"
if not (len(password) >= 8):
    print("パスワードが短すぎます")

# 複雑な条件
score = 85
attendance = 90

if (score >= 80 and attendance >= 80) or score >= 95:
    print("合格です")

実行結果:

ローンの審査に通ります
パスワードが短すぎます
合格です

よくある質問(FAQ)

Q1:None と 0 や空文字列の違いは?

A1: Noneは「値が存在しない」ことを表す特別な値で、0や空文字列とは異なります。

values = [None, 0, "", False, []]

for value in values:
    if value is None:
        print(f"{value} は None です")
    elif value == False:  # 0, "", False, [] はすべてFalseと等価
        print(f"{value} は False と等価です")
    else:
        print(f"{value} はその他の値です")

Q2:リストの一部だけを比較したいときは?

A2: スライスを使って部分的に比較できます。

list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 6, 7]

# 最初の3要素だけ比較
print(f"最初の3要素が同じ: {list1[:3] == list2[:3]}")  # True

Q3:辞書の比較はどうなる?

A3: 辞書は順序に関係なく、キーと値のペアが同じかどうかで比較されます。

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 2, "a": 1}  # 順序が違う

print(f"辞書の比較: {dict1 == dict2}")  # True(内容が同じ)

まとめ

Pythonの比較演算子は、プログラムの判断処理において不可欠な機能です。

重要なポイント:

  • 比較演算子は必ずTrueまたはFalseを返す
  • ==は値の比較、isはオブジェクトの比較
  • 文字列は辞書順、リストは要素順で比較される
  • =(代入)と==(比較)を混同しない
  • 異なる型の比較には注意が必要
  • 連続比較でコードを読みやすくできる

コメント

タイトルとURLをコピーしました