論理演算子:andとorとnot#
はじめに#
前回の記事では、比較演算子について学びました。今回は、真偽値を組み合わせるための「論理演算子」について詳しく見ていきましょう。
論理演算子は、複数の条件を組み合わせて、より複雑な条件を作るための演算子です。例えば「AかつB」「AまたはB」「Aでない」といった条件を表現できます。
基本的な論理演算子#
Pythonには、3つの基本的な論理演算子があります。
演算子 | 意味 | 例 |
---|---|---|
and | 論理積(AND):両方がTrueのときだけTrue | a and b |
or | 論理和(OR):少なくとも1つがTrueならTrue | a or b |
not | 論理否定(NOT):真偽値を反転 | not a |
以下の例で、これらの論理演算子を試してみましょう。
>
# 論理演算子の基本
a = True
b = False
# and演算子(両方真の場合に真)
print(f"{a} and {a}: {a and a}")
print(f"{a} and {b}: {a and b}")
print(f"{b} and {b}: {b and b}")
# or演算子(少なくとも一方が真の場合に真)
print(f"{a} or {a}: {a or a}")
print(f"{a} or {b}: {a or b}")
print(f"{b} or {b}: {b or b}")
# not演算子(真偽を反転)
print(f"not {a}: {not a}")
print(f"not {b}: {not b}")
実行結果:
True and True: True
True and False: False
False and False: False
True or True: True
True or False: True
False or False: False
not True: False
not False: True
真理値表#
論理演算子の動作をまとめると、次のような「真理値表」になります。
ANDの真理値表#
A | B | A and B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
ORの真理値表#
A | B | A or B |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
NOTの真理値表#
A | not A |
---|---|
True | False |
False | True |
複合条件の作成#
論理演算子を使うことで、複数の条件を組み合わせて、より複雑な条件を作ることができます。
>
# 複合条件の例
age = 25
has_id = True
is_student = False
# 複数の条件を組み合わせる
can_vote = age >= 18 and has_id
print(f"投票できるか?: {can_vote}")
# より複雑な条件
gets_discount = is_student or age < 18 or age >= 65
print(f"割引を受けられるか?: {gets_discount}")
実行結果:
投票できるか?: True
割引を受けられるか?: False
論理演算子の評価順序#
複数の論理演算子を組み合わせる場合、評価順序が重要になります。Pythonでは次の順序で評価されます。
not
(最も優先度が高い)and
or
(最も優先度が低い)
複雑な条件を書く場合は、かっこ()
を使って優先順位を明示することをお勧めします。
>
# 論理演算子の評価順序
a = True
b = False
c = True
# かっこがない場合
result1 = not a and b or c
print(f"not a and b or c: {result1}") # notが先に評価される
# かっこを使って優先順位を明示
result2 = not (a and b or c) # かっこ内が先に評価される
print(f"not (a and b or c): {result2}"))
実行結果:
not a and b or c: True
not (a and b or c): False
not a and b or c
の評価順序は、not
が最初に評価され、その後にand
とor
が評価されます。not (a and b or c)
の場合は、かっこ内のa and b or c
が先に評価され、その結果に対してnot
が適用されます。
論理演算子と比較演算子の組み合わせ#
論理演算子と比較演算子を組み合わせることで、より複雑な条件を表現できます。
>
# 論理演算子と比較演算子の組み合わせ
x = 10
y = 20
z = 15
# 範囲チェック
is_in_range = x > 0 and x < 100
print(f"{x} は 0 から 100 の範囲内か?: {is_in_range}")
# 複数の条件
complex_condition = (x < y and y > z) or (x == 10 and z != 0)
print(f"複雑な条件の結果: {complex_condition}")
# 読みやすい方法
is_valid_x = 0 < x < 100 # 連鎖比較演算子
is_y_greater = y > x and y > z
is_special_case = x == 10 and z != 0
# 条件を組み合わせる
final_result = is_valid_x and (is_y_greater or is_special_case)
print(f"最終結果: {final_result}")
実行結果:
10 は 0 から 100 の範囲内か?: True
複雑な条件の結果: True
最終結果: True
まとめ#
この記事では、Pythonの論理演算子について詳しく学びました。
- 基本的な論理演算子(
and
,or
,not
)の使い方 - 論理演算子の真理値表
- 複合条件の作成方法
- 論理演算子の評価順序と優先順位
- 論理演算子と比較演算子の組み合わせ方
論理演算子は条件分岐や繰り返し処理で頻繁に使用されます。複雑な条件を正確に表現するためには、論理演算子の挙動をしっかり理解することが重要です。
次回の記事では、これまで学んだ真偽値、比較演算子、論理演算子の知識を活かして、条件分岐(if文)について学んでいきます。
目次