Python演算子
Python演算子
演算子は、変数と値の操作を実行するために使用されます。
以下の例では、+
演算子を使用して2つの値を加算します。
例
print(10 + 5)
Pythonは、演算子を次のグループに分けます。
- 算術演算子
- 代入演算子
- 比較演算子
- 論理演算子
- ID演算子
- メンバーシップオペレーター
- ビット演算子
Python算術演算子
算術演算子は、一般的な数学演算を実行するために数値とともに使用されます。
Operator | Name | Example | Try it |
---|---|---|---|
+ | Addition | x + y | |
- | Subtraction | x - y | |
* | Multiplication | x * y | |
/ | Division | x / y | |
% | Modulus | x % y | |
** | Exponentiation | x ** y | |
// | Floor division | x // y |
Python代入演算子
代入演算子は、変数に値を代入するために使用されます。
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
//= | x //= 3 | x = x // 3 | |
**= | x **= 3 | x = x ** 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
Python比較演算子
比較演算子は、次の2つの値を比較するために使用されます。
Operator | Name | Example | Try it |
---|---|---|---|
== | Equal | x == y | |
!= | Not equal | x != y | |
> | Greater than | x > y | |
< | Less than | x < y | |
>= | Greater than or equal to | x >= y | |
<= | Less than or equal to | x <= y |
Python論理演算子
論理演算子は、条件ステートメントを組み合わせるために使用されます。
Operator | Description | Example | Try it |
---|---|---|---|
and | Returns True if both statements are true | x < 5 and x < 10 | |
or | Returns True if one of the statements is true | x < 5 or x < 4 | |
not | Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
PythonID演算子
ID演算子は、オブジェクトが等しい場合ではなく、実際には同じオブジェクトであり、同じメモリ位置にある場合に、オブジェクトを比較するために使用されます。
Operator | Description | Example | Try it |
---|---|---|---|
is | Returns True if both variables are the same object | x is y | |
is not | Returns True if both variables are not the same object | x is not y |
Pythonメンバーシップ演算子
メンバーシップ演算子は、シーケンスがオブジェクトに表示されているかどうかをテストするために使用されます。
Operator | Description | Example | Try it |
---|---|---|---|
in | Returns True if a sequence with the specified value is present in the object | x in y | |
not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
Pythonビット演算子
ビット単位の演算子は、(2進数の)数値を比較するために使用されます。
Operator | Name | Description |
---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Sets each bit to 1 if one of two bits is 1 |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
~ | NOT | Inverts all the bits |
<< | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |