Python比較演算子入門|大小比較と等価判定の基礎
Python初心者向けの比較演算子完全ガイド。大小比較、等価判定、不等価判定の基本的な使い方から実際のコード例まで分かりやすく解説。
Pythonで数値や文字列を比較する時、どの演算子を使えばいいか迷ったことはありませんか?
「大小比較はどうやるの?」 「等価判定と不等価判定の違いは?」 「文字列の比較もできるの?」
そんな疑問を持っている方も多いはず。 でも大丈夫です!
この記事では、Python初心者が知っておくべき比較演算子の基本を詳しく解説します。 大小比較から等価判定まで、実際のコード例とともに理解できるはずです。
比較演算子って何?
比較演算子は、2つの値を比較してTrueまたはFalseを返す演算子です。
比較演算子の種類
Pythonには6つの基本的な比較演算子があります:
# Python比較演算子の基本例a = 10b = 5c = 10
print("=== 基本的な比較演算子 ===")
# 等価演算子(==)print(f"a == c: {a == c}") # True
# 不等価演算子(!=)print(f"a != b: {a != b}") # True
# 大なり演算子(>)print(f"a > b: {a > b}") # True
# 小なり演算子(<)print(f"b < a: {b < a}") # True
# 以上演算子(>=)print(f"a >= c: {a >= c}") # True
# 以下演算子(<=)print(f"b <= a: {b <= a}") # True
このコードでは、6つの基本的な比較演算子を使っています。
a == c
で、aとcが等しいかチェック。
a != b
で、aとbが等しくないかチェック。
a > b
で、aがbより大きいかチェックしています。
各演算子は、条件が満たされればTrue、満たされなければFalseを返します。
実際の使用例
比較演算子は、文字列の比較にも使えます:
# 文字列比較の例name1 = "Alice"name2 = "Bob"name3 = "Alice"
print("=== 文字列比較の例 ===")print(f"name1 = '{name1}', name2 = '{name2}', name3 = '{name3}'")
print(f"name1 == name3: {name1 == name3}") # Trueprint(f"name1 != name2: {name1 != name2}") # Trueprint(f"name1 < name2: {name1 < name2}") # True (辞書順)print(f"name2 > name1: {name2 > name1}") # True (辞書順)
文字列の比較では、辞書順(アルファベット順)で比較されます。
この例では、「Alice」が「Bob」より辞書順で前なので、name1 < name2
がTrueになります。
数値の大小比較
数値の大小比較は、プログラミングで最も頻繁に使用される比較の一つです。
整数と浮動小数点数の比較
# 数値比較の詳細な例print("=== 数値比較の詳細例 ===")
# 整数同士の比較print("--- 整数同士の比較 ---")x = 15y = 20
print(f"x = {x}, y = {y}")print(f"x < y: {x < y}") # Trueprint(f"x > y: {x > y}") # Falseprint(f"x <= y: {x <= y}") # Trueprint(f"x >= y: {x >= y}") # False
# 浮動小数点数の比較print("--- 浮動小数点数の比較 ---")price1 = 19.99price2 = 25.50
print(f"price1 = {price1}, price2 = {price2}")print(f"price1 < price2: {price1 < price2}") # Trueprint(f"price1 > price2: {price1 > price2}") # False
# 整数と浮動小数点数の混合比較print("--- 混合比較 ---")integer_value = 10float_value = 10.5
print(f"integer_value = {integer_value}, float_value = {float_value}")print(f"integer_value < float_value: {integer_value < float_value}") # Trueprint(f"integer_value == float_value: {integer_value == float_value}") # False
この例では、異なる数値型の比較を行っています。
整数同士の比較では、普通の数学と同じように動作。 浮動小数点数も同様に比較できます。 整数と浮動小数点数を混合しても、問題なく比較できるんです。
実用的な範囲チェック
数値比較の実用的な例として、年齢カテゴリの判定を見てみましょう:
# 実用的な範囲チェックdef check_age_category(age): """年齢カテゴリを判定する関数""" if age < 0: return "無効な年齢" elif age < 18: return "未成年" elif age < 65: return "成人" else: return "高齢者"
print("--- 実用的な範囲チェック ---")ages = [5, 16, 25, 70, -1]
for age in ages: category = check_age_category(age) print(f"年齢 {age}: {category}")
この関数では、複数の比較演算子を組み合わせています。
まず、age < 0
で無効な年齢をチェック。
次に、age < 18
で未成年をチェック。
そして、age < 65
で成人をチェックしています。
このように、比較演算子を使うことで複雑な条件分岐が簡単に書けます。
等価判定と不等価判定
等価判定は、2つの値が同じかどうかを確認する重要な比較です。
基本的な等価判定
# 等価判定の基本print("=== 等価判定の基本 ===")
# 数値の等価判定print("--- 数値の等価判定 ---")num1 = 42num2 = 42num3 = 40 + 2
print(f"num1 = {num1}, num2 = {num2}, num3 = {num3}")print(f"num1 == num2: {num1 == num2}") # Trueprint(f"num1 == num3: {num1 == num3}") # Trueprint(f"num1 != num2: {num1 != num2}") # False
# 文字列の等価判定print("--- 文字列の等価判定 ---")text1 = "Hello"text2 = "Hello"text3 = "hello" # 小文字
print(f"text1 = '{text1}', text2 = '{text2}', text3 = '{text3}'")print(f"text1 == text2: {text1 == text2}") # Trueprint(f"text1 == text3: {text1 == text3}") # False (大文字小文字区別)print(f"text1 != text3: {text1 != text3}") # True
数値の等価判定では、計算結果も正しく比較されます。 文字列の等価判定では、大文字と小文字が区別されることに注意が必要です。
大文字小文字を無視した比較
文字列の比較で大文字小文字を無視したい場合は、工夫が必要です:
# 大文字小文字を無視した比較def case_insensitive_compare(str1, str2): """大文字小文字を無視して比較""" return str1.lower() == str2.lower()
print("--- 大文字小文字を無視した比較 ---")print(f"case_insensitive_compare('Hello', 'hello'): {case_insensitive_compare('Hello', 'hello')}") # Trueprint(f"case_insensitive_compare('Python', 'PYTHON'): {case_insensitive_compare('Python', 'PYTHON')}") # True
この関数では、lower()
メソッドで両方の文字列を小文字に変換してから比較しています。
これにより、大文字小文字に関係なく文字列を比較できます。
浮動小数点数の注意点
浮動小数点数の等価判定には、特別な注意が必要です:
# 浮動小数点数の注意点print("--- 浮動小数点数の注意点 ---")
# 浮動小数点数の誤差result1 = 0.1 + 0.2result2 = 0.3
print(f"0.1 + 0.2 = {result1}")print(f"0.3 = {result2}")print(f"0.1 + 0.2 == 0.3: {result1 == result2}") # False(浮動小数点誤差)
# 浮動小数点数の安全な比較def is_close(a, b, tolerance=1e-9): """浮動小数点数の安全な比較""" return abs(a - b) < tolerance
print(f"is_close(0.1 + 0.2, 0.3): {is_close(0.1 + 0.2, 0.3)}") # True
浮動小数点数では、計算誤差により期待した結果にならない場合があります。
そのため、is_close()
のような関数を使って安全に比較することをおすすめします。
文字列の比較
文字列の比較は、**辞書順(アルファベット順)**に基づいて行われます。
辞書順での比較
# 文字列比較の詳細例print("=== 文字列比較の詳細例 ===")
# 基本的な辞書順比較print("--- 基本的な辞書順比較 ---")words = ["apple", "banana", "cherry", "date"]
print(f"単語リスト: {words}")
# 隣接する単語の比較for i in range(len(words) - 1): word1 = words[i] word2 = words[i + 1] print(f"'{word1}' < '{word2}': {word1 < word2}") print(f"'{word1}' > '{word2}': {word1 > word2}")
この例では、単語のリストを辞書順で比較しています。
「apple」は「banana」より辞書順で前なので、apple < banana
がTrueになります。
大文字と小文字の比較
文字列比較では、大文字と小文字の扱いに注意が必要です:
# 大文字と小文字の比較print("--- 大文字と小文字の比較 ---")upper_case = "APPLE"lower_case = "apple"mixed_case = "Apple"
print(f"upper_case = '{upper_case}'")print(f"lower_case = '{lower_case}'")print(f"mixed_case = '{mixed_case}'")
# ASCII値に基づく比較print(f"'{upper_case}' < '{lower_case}': {upper_case < lower_case}") # True(大文字のASCII値が小さい)print(f"'{mixed_case}' < '{lower_case}': {mixed_case < lower_case}") # True
大文字は小文字よりもASCII値が小さいため、辞書順で前に来ます。 そのため、「APPLE」は「apple」より小さいと判定されます。
実用的な名前のソート
文字列比較の実用例として、名前のソートを見てみましょう:
# 実用的な例:名前のソートdef sort_names(names): """名前をソートする関数""" return sorted(names)
def sort_names_ignore_case(names): """大文字小文字を無視してソートする関数""" return sorted(names, key=str.lower)
print("--- 実用的な例:名前のソート ---")name_list = ["John", "alice", "Bob", "charlie"]
print(f"元のリスト: {name_list}")print(f"通常のソート: {sort_names(name_list)}")print(f"大文字小文字無視: {sort_names_ignore_case(name_list)}")
通常のソートでは、大文字が小文字より前に来ます。 大文字小文字を無視したソートでは、純粋にアルファベット順でソートされます。
実践的な比較演算子の使い方
比較演算子を使った実践的なプログラミング例を見てみましょう。
条件分岐での活用
# 成績判定システムdef grade_calculator(score): """成績を判定する関数""" if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F"
# 複数の成績を判定print("--- 成績判定システム ---")test_scores = [95, 87, 76, 63, 58, 42]
for score in test_scores: grade = grade_calculator(score) print(f"点数 {score}: {grade}")
この成績判定システムでは、比較演算子を使って点数に応じた成績を決定しています。
score >= 90
で最高評価のAを判定。
score >= 80
でBを判定。
このように順番に条件をチェックしています。
年齢に基づく料金計算
もう一つの実用例として、年齢に基づく料金計算を見てみましょう:
# 年齢に基づく料金計算def calculate_ticket_price(age): """年齢に基づいてチケット料金を計算""" if age < 0: return "無効な年齢" elif age < 3: return "無料" elif age < 12: return "子供料金: 500円" elif age < 65: return "大人料金: 1000円" else: return "シニア料金: 700円"
print("--- 年齢に基づく料金計算 ---")ages = [2, 8, 25, 70, 90]
for age in ages: price = calculate_ticket_price(age) print(f"年齢 {age}: {price}")
この例では、年齢に応じて異なる料金を設定しています。 比較演算子を使うことで、複雑な料金体系も簡潔に表現できます。
範囲チェック
値が特定の範囲内にあるかチェックする例も見てみましょう:
# 範囲チェックdef is_in_range(value, min_val, max_val): """値が指定された範囲内にあるかチェック""" return min_val <= value <= max_val
# 体温の正常範囲チェックdef check_temperature(temp): """体温が正常範囲内かチェック""" if is_in_range(temp, 35.0, 37.5): return "正常" elif temp < 35.0: return "低体温" else: return "発熱"
print("--- 範囲チェック ---")temperatures = [34.5, 36.2, 37.8, 38.5]
for temp in temperatures: status = check_temperature(temp) print(f"体温 {temp}°C: {status}")
この例では、min_val <= value <= max_val
という連続した比較を使っています。
Pythonでは、このような連続比較が自然に書けるので便利です。
まとめ
Python比較演算子について、基本的な概念から実践的な使い方まで詳しく解説しました。
重要なポイント:
- 6つの基本比較演算子(==, !=, <, >, <=, >=)をマスターする
- 数値比較では整数と浮動小数点数を自由に比較できる
- 文字列比較は辞書順(Unicode順)で行われる
- 浮動小数点数の等価判定には注意が必要
- 実践的な活用で複雑な判定ロジックを作成できる
比較演算子は、条件分岐やデータ検証など、プログラミングの基礎となる重要な機能です。 これらの知識を活用して、様々な場面で比較演算子を使いこなしてみてください。
効率的で読みやすいコードを書くために、ぜひ比較演算子をマスターしてくださいね!