Operators in Python
This article explains operators in Python.
YouTube Video
Operators in Python
Python has various operators, which can be broadly categorized as follows. We will explain representative operators for each category.
Arithmetic Operators
Arithmetic operators are operators used to perform calculations on numbers.
Operator | Meaning | Example |
---|---|---|
+ |
Addition | 3 + 2 → 5 |
- |
Subtraction | 3 - 2 → 1 |
* |
Multiplication | 3 * 2 → 6 |
/ |
Division (always float) | 3 / 2 → 1.5 |
// |
Floor division | 3 // 2 → 1 |
% |
Remainder (modulo) | 3 % 2 → 1 |
** |
Exponentiation | 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
- In addition to the four basic arithmetic operations, Python provides operators for division (
/
), integer division (//
), modulus (%
), and exponentiation (**
). Division returns a floating-point number even when dividing integers.
Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Meaning | Example |
---|---|---|
= |
Assignment | x = 5 |
+= |
Add and assign | x += 2 → x = x + 2 |
-= |
Subtract and assign | x -= 2 → x = x - 2 |
*= |
Multiply and assign | x *= 2 → x = x * 2 |
/= |
Divide and assign | x /= 2 → x = x / 2 |
//= |
Floor division | x //= 2 → x = x // 2 |
%= |
Assign remainder | x %= 2 → x = x % 2 |
**= |
Assign exponentiation | x **= 2 → x = x ** 2 |
&= |
Assign using AND | x &= 0b1010 → x = x & 0b1010 |
|= |
Assign using OR | x | = 0b0011 →x = x | 0b0011 |
^= |
Assign using XOR | x ^= 0b0101 → x = x ^ 0b0101 |
<<= |
Assign after left shift | x <<= 2 → x = x << 2 |
>>= |
Assign after right shift | x >>= 1 → x = x >> 1 |
:= |
Assignment expression (walrus operator) | if (n := len(data)) > 10: → Assign to n while evaluating the condition |
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}")
- Assignment operators allow combining standard assignment with various operators to assign the result.
- The walrus operator (
:=
) is an assignment expression available in Python 3.8 and later. - While standard assignment can only be used as a statement, the walrus operator allows assignment within an expression.
Comparison Operators
Comparison operators compare values and return True
or False
.
Operator | Meaning | Example |
---|---|---|
== |
Equal | 3 == 3 → True |
!= |
Not equal | 3 != 4 → True |
> |
Greater than | 5 > 2 |
< |
Less than | 5 < 2 |
>= |
Greater than or equal to | 5 >= 5 |
<= |
Less than or equal to | 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
- Comparison operators compare two values for order or equality and return
True
orFalse
as a result. - In Python, you should be careful when comparing different data types. Some types can be compared with each other, but the results may not be intuitive.
Logical Operators
Logical operators are used to combine logical expressions.
Operator | Meaning | Example |
---|---|---|
and |
Returns True if both are True | True and False → False |
or |
Returns True if either is True | True or False → True |
not |
Inverts the boolean value | 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
is a logical operator that returnsTrue
only if both conditions on the left and right areTrue
.or
is a logical operator that returnsTrue
if either the left or right condition isTrue
.not
is a logical operator that inverts the truth value of a condition. If it is True, it becomes False, and if it is False, it becomes True.
Precedence of logical operators
Operators have precedence. This is the rule that determines which operator is evaluated first in an expression. Logical operators are evaluated in the order: not
, and
, then or
.
1result = True or False and False
2print(result) # True
3
4result = (True or False) and False
5print(result) # False
たとえば、
In the first example, and
is evaluated first, so False and False
becomes False
, and as a result, True or False
becomes True
. You can also change the order of evaluation by using parentheses, as shown in the second example.
Bitwise Operators
Bitwise operators perform operations at the bit level.
Operator | Meaning | Example |
---|---|---|
& |
Bitwise AND | 5 & 3 → 1 |
| |
Bitwise OR | 5 | 3 →7 |
^ |
Bitwise exclusive OR (XOR) | 5 ^ 3 → 6 |
~ |
Bitwise NOT | ~5 → -6 |
<< |
Left shift | 5 << 1 → 10 |
>> |
Right shift | 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}")
- You can perform bitwise AND, OR, XOR, NOT operations, as well as bit shift operations. You can also combine them with assignment operators like
&=
.
Membership Operators
Membership operators are used with collections such as lists and dictionaries.
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
- The
in
operator is used to determine whether a specified value is contained in a sequence such as a list or string, or a collection such as a dictionary. - The
not in
operator is used to determine whether a specified value is not contained in a sequence or collection.
Identity Operators
Identity operators check the identity of objects.
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
- The
is
operator checks whether two objects are the same object (i.e., refer to the same memory location). - The
is not
operator checks whether two objects are different objects. - For example,
x is y
differs fromx == y
in that it checks object identity, not value equality.
Type Checking
In Python, you use the isinstance()
function to check if a value is of a specific type. You can also use the type()
function to check the exact type of a variable. Although these are not operators, they are basic mechanisms for type checking.
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()
is a function that checks whether an object is an instance of a specified class or its subclass.type()
is a function that returns the exact type (class) of an object. It is usually used when you want to perform strict type comparison.isinstance()
considers inheritance relationships, whiletype()
checks for exact matches.
Summary
When using each operator, you need to choose appropriately based on its purpose and type. Since Python is a dynamically typed language, the result of an operation may vary depending on the type of values being calculated.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.