Pythonにおける演算子
この記事ではPythonにおける演算子について説明します。
YouTube Video
Pythonにおける演算子
Pythonにはさまざまな演算子がありますが、大きく分けて以下のカテゴリに分類できます。それぞれのカテゴリに属する代表的な演算子について説明します。
算術演算子
算術演算子は数値の計算を行うための演算子です。
演算子 | 意味 | 例 |
---|---|---|
+ |
加算 | 3 + 2 → 5 |
- |
減算 | 3 - 2 → 1 |
* |
乗算 | 3 * 2 → 6 |
/ |
除算(常にfloat) | 3 / 2 → 1.5 |
// |
切り捨て除算 | 3 // 2 → 1 |
% |
剰余(あまり) | 3 % 2 → 1 |
** |
べき乗 | 3 ** 2 → 9 |
1a = 10
2b = 3
3
4print(f"{a} + {b} = {a + b}") # Addition
5print(f"{a} - {b} = {a - b}") # Subtraction
6print(f"{a} * {b} = {a * b}") # Multiplication
7print(f"{a} / {b} = {a / b}") # Division (float)
8print(f"6 / 3 = {6 / 3}") # Division (float)
9print(f"{a} // {b} = {a // b}") # Floor Division
10print(f"{a} % {b} = {a % b}") # Modulo (remainder)
11print(f"{a} ** {b} = {a ** b}") # Exponentiation
- Pythonには、四則演算に加え、除算(
/
)や整数での除算(//
)、剰余(%
)や累乗(**
)を行う演算子があります。除算は、整数で割っても浮動小数点数を返します。
代入演算子
代入演算子は変数に値を代入するために使います。
演算子 | 意味 | 例 |
---|---|---|
= |
代入 | x = 5 |
+= |
加算して代入 | x += 2 → x = x + 2 |
-= |
減算して代入 | x -= 2 → x = x - 2 |
*= |
乗算して代入 | x *= 2 → x = x * 2 |
/= |
除算して代入 | x /= 2 → x = x / 2 |
//= |
切り捨て除算 | x //= 2 → x = x // 2 |
%= |
剰余を代入 | x %= 2 → x = x % 2 |
**= |
べき乗を代入 | x **= 2 → x = x ** 2 |
&= |
ANDを代入 | x &= 0b1010 → x = x & 0b1010 |
|= |
ORを代入 | x | = 0b0011 →x = x | 0b0011 |
^= |
XORを代入 | x ^= 0b0101 → x = x ^ 0b0101 |
<<= |
左シフトして代入 | x <<= 2 → x = x << 2 |
>>= |
右シフトして代入 | x >>= 1 → x = x >> 1 |
:= |
代入式(ワルラス演算子) | if (n := len(data)) > 10: → nに代入しながら条件判定 |
1x = 5 # x = 5
2
3x += 3 # x = x + 3
4x -= 2 # x = x - 2
5x *= 4 # x = x * 4
6x /= 3 # x = x / 3
7x //= 2 # x = x // 2
8x %= 5 # x = x % 5
9x **= 3 # x = x ** 3
10
11x = 0b1100 # x = 0b1100 (12)
12
13x &= 0b1010 # x = x & 0b1010
14x |= 0b0011 # x = x | 0b0011
15x ^= 0b0101 # x = x ^ 0b0101
16x <<= 2 # x = x << 2
17x >>= 1 # x = x >> 1
18
19print(bin(x)) # Display in binary
20print(x) # Display in decimal
21
22# Walrus operator
23if (n := len("hello")) > 3:
24 print(f"Length is {n}")
- 代入演算子では、通常の代入に加え、各演算子と組み合わせて結果を代入することもできます。
- ワルラス演算子(
:=
)は、Python 3.8 以降で使用可能な「代入式」です。 - 通常の代入はステートメントとしてしか使えませんが、ワルラス演算子は式の中で代入を行えます。
比較演算子
比較演算子は、値の比較を行い、True
またはFalse
を返します。
演算子 | 意味 | 例 |
---|---|---|
== |
等しい | 3 == 3 → True |
!= |
等しくない | 3 != 4 → True |
> |
より大きい | 5 > 2 |
< |
より小さい | 5 < 2 |
>= |
以上 | 5 >= 5 |
<= |
以下 | 3 <= 4 |
1a = 10
2b = 20
3
4# Equal to (==)
5print(f"{a} == {b} -> {a == b}") # False: a and b are not equal
6print(f"3 == 3.0 -> {3 == 3.0}") # True: int and float with the same value are equal
7print(f"3 == '3' -> {3 == '3'}") # False: different types (int vs str)
8print(f"True == 1 -> {True == 1}") # True: True is equivalent to 1
9print(f"False == 0 -> {False == 0}") # True: False is equivalent to 0
10print(f"None == 0 -> {None == 0}") # False: None is not equal to 0
11
12# Not equal to (!=)
13print(f"{a} != {b} -> {a != b}") # True: a and b are not equal
14
15# Greater than (>)
16print(f"{b} > {a} -> {b > a}") # True: 20 > 10
17
18# Less than (<)
19print(f"{a} < {b} -> {a < b}") # True: 10 < 20
20
21# Greater than or equal to (>=)
22print(f"{a} >= 10 -> {a >= 10}") # True: a is greater than or equal to 10
23
24# Less than or equal to (<=)
25print(f"{a} <= 10 -> {a <= 10}") # True: a is less than or equal to 10
- 比較演算子では、2つの値の大小や等しさを比較し、その結果として
True
またはFalse
を返します。 - Pythonでは、異なるデータ型同士の比較を行うときに注意が必要です。一部の型同士は比較可能ですが、意味が直感と異なることがあります。
論理演算子
論理演算子は、論理式を組み合わせる際に使用されます。
演算子 | 意味 | 例 |
---|---|---|
and |
両方がTrueならTrue | True and False → False |
or |
どちらかがTrueならTrue | True or False → True |
not |
真偽値を反転 | not True → False |
1x = 10
2print(x > 5 and x < 20) # True
3print(x < 5 or x > 20) # False
4print(not x == 10) # False
and
は、左右の条件が両方とも真(True
)の場合に真を返す論理演算子です。or
は、左右のいずれかの条件が真(True
)であれば真を返す論理演算子です。not
は、条件の真偽を反転させる論理演算子です。真(True
)であれば偽(False
)に、偽であれば真に変わります。
論理演算子の優先順位
演算子には優先順位があります。これは、式の中でどの演算子を先に計算するかを決めるルールです。論理演算子は、not
、and
、or
の順で評価されます。
1result = True or False and False
2print(result) # True
3
4result = (True or False) and False
5print(result) # False
たとえば、
最初の例では、and
が先に評価されるため、False and False
はFalse
になり、True or False
の結果としてTrue
になります。二番目の例のように括弧を使えば、計算の順番を変えることもできます。
ビット演算子
ビット演算子はビット単位の演算を行います。
演算子 | 意味 | 例 |
---|---|---|
& |
ビット積(AND) | 5 & 3 → 1 |
| |
ビット和(OR) | 5 | 3 →7 |
^ |
排他的論理和(XOR) | 5 ^ 3 → 6 |
~ |
ビット反転(NOT) | ~5 → -6 |
<< |
左シフト | 5 << 1 → 10 |
>> |
右シフト | 5 >> 1 → 2 |
1# Sample code for bitwise operators
2
3# Define two integers
4a = 5 # Binary: 0101
5b = 3 # Binary: 0011
6
7# Bitwise AND
8result_and = a & b # Binary: 0001 -> Decimal: 1
9print(f"{a} & {b} = {result_and}")
10
11# Bitwise OR
12result_or = a | b # Binary: 0111 -> Decimal: 7
13print(f"{a} | {b} = {result_or}")
14
15# Bitwise XOR
16result_xor = a ^ b # Binary: 0110 -> Decimal: 6
17print(f"{a} ^ {b} = {result_xor}")
18
19# Bitwise NOT (inverting bits)
20result_not = ~a # Binary: -(0101 + 1) -> Decimal: -6
21print(f"~{a} = {result_not}")
22
23# Left shift
24shift_left = a << 1 # Binary: 1010 -> Decimal: 10
25print(f"{a} << 1 = {shift_left}")
26
27# Right shift
28shift_right = a >> 1 # Binary: 0010 -> Decimal: 2
29print(f"{a} >> 1 = {shift_right}")
- ビットごとのAND, OR, XOR, NOTの演算や、ビットシフト演算を行うことができます。また、
&=
のように代入演算子と組み合わせて使うこともできます。
メンバーシップ演算子
メンバーシップ演算子はリストやディクショナリなどのコレクションに対して使用されます。
1x = [1, 2, 3]
2y = 2
3z = 4
4
5print("y in x : ", y in x) # Result is True
6print("z in x : ", z in x) # Result is False
7
8print("y not in x : ", y not in x) # Result is False
9print("z not in x : ", z not in x) # Result is True
10
11text = "hello world"
12print("'world' in 'hello world' : ", "world" in text) # True
13print("'python' not in 'hello world' : ", "python" not in text) # True
in
演算子は、指定した値がリスト、文字列などのシーケンスや、辞書などのコレクションに含まれているかを判定する演算子です。not in
演算子は、指定した値がシーケンスやコレクションに含まれていないかを判定する演算子です。
同一性演算子
同一性演算子はオブジェクトの同一性を確認します。
1x = [1, 2, 3]
2y = x
3z = x.copy()
4
5print("x is y : ", x is y) # Result is True
6print("x is z : ", x is z) # Result is False
7
8print("x is not y : ", x is not y) # Result is False
9print("x is not z : ", x is not z) # Result is True
10
11print("x == y : ", x == y) # Result is True
12print("x == z : ", x == z) # Result is True
is
演算子は、2つのオブジェクトが同じオブジェクトであるか(同一のメモリ領域を指しているか)を判定する演算子です。is not
演算子は、2つのオブジェクトが異なるオブジェクトであるかを判定する演算子です。- たとえば、
x is y
はx == y
とは異なり、値の等価性ではなくオブジェクトの同一性をチェックします。
型判定
Pythonでは、値が特定の型であるかを調べるために、isinstance()
関数を使います。また、type()
関数を使えば、変数の正確な型を調べることもできます。これらは演算子ではありませんが、型に関する判定を行う基本的な仕組みです。
1x = 10
2print(isinstance(x, int)) # True
3
4y = "hello"
5print(isinstance(y, str)) # True
6
7z = [1, 2, 3]
8print(isinstance(z, list)) # True
9
10print(type(10)) # <class 'int'>
11print(type("hello")) # <class 'str'>
12
13print("isinstance(3, int) : ", isinstance(3, int)) # True
14print("type(3) is int : ", type(3) is int) # True
15print("type(True) is bool : ", type(True) is bool) # True
isinstance()
は、オブジェクトが指定されたクラスまたはそのサブクラスのインスタンスかどうかを判定する関数です。type()
は、オブジェクトの正確な型(クラス)を返す関数です。通常、厳密な型比較を行いたいときに使用されます。isinstance()
は継承関係も考慮して判定しますが、type()
は完全一致を見ます。
まとめ
それぞれの演算子を使用するときは、用途や型に合わせて適切に選択する必要があります。Pythonは動的型付け言語なので、計算する値の型によって演算結果が異なる場合があります。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。