In this tutorial, you'll explore the different types of operators available in Python, including arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Understanding these operators is crucial for performing operations on data and controlling the flow of your programs. Additionally, we'll delve into operator precedence to ensure that expressions are evaluated correctly.
Operators in Python allow you to perform various operations on variables and values. They can be categorized into several types:
Understanding these operators and their precedence will help you write more effective and efficient Python code.
Arithmetic operators are used for basic mathematical operations such as addition, subtraction, multiplication, division, modulus, exponentiation, and floor division.
| Operator | Description | Example |
|---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 5 / 3 = 1.6667 |
% | Modulus | 5 % 3 = 2 |
** | Exponentiation | 5 ** 3 = 125 |
// | Floor Division | 5 // 3 = 1 |
1a = 52b = 334print("Addition:", a + b)5print("Subtraction:", a - b)6print("Multiplication:", a * b)7print("Division:", a / b)8print("Modulus:", a % b)9print("Exponentiation:", a ** b)10print("Floor Division:", a // b)
Addition: 8 Subtraction: 2 Multiplication: 15 Division: 1.6666666666666667 Modulus: 2 Exponentiation: 125 Floor Division: 1
Assignment operators are used to assign values to variables. They can also perform operations and then assign the result back to the variable.
| Operator | Example | Equivalent To |
|---|---|---|
= | 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 |
1x = 52print("Initial value of x:", x)34x += 35print("After x += 3:", x)67x -= 28print("After x -= 2:", x)910x *= 411print("After x *= 4:", x)1213x /= 214print("After x /= 2:", x)1516x %= 517print("After x %= 5:", x)1819x **= 320print("After x **= 3:", x)2122x //= 223print("After x //= 2:", x)
Initial value of x: 5 After x += 3: 8 After x -= 2: 6 After x *= 4: 24 After x /= 2: 12.0 After x %= 5: 2.0 After x **= 3: 8.0 After x //= 2: 4.0
Comparison operators are used to compare two values and return a Boolean result (True or False). These operators are essential for decision-making in your programs.
| Operator | Description | Example |
|---|---|---|
== | Equal | 5 == 3 returns False |
!= | Not equal | 5 != 3 returns True |
> | Greater than | 5 > 3 returns True |
< | Less than | 5 < 3 returns False |
>= | Greater than or equal | 5 >= 3 returns True |
<= | Less than or equal | 5 <= 3 returns False |
1a = 52b = 334print("a == b:", a == b)5print("a != b:", a != b)6print("a > b:", a > b)7print("a < b:", a < b)8print("a >= b:", a >= b)9print("a <= b:", a <= b)
a == b: False a != b: True a > b: True a < b: False a >= b: True a <= b: False
Logical operators are used to combine conditional statements. They return a Boolean result based on the conditions provided.
| Operator | Description | Example |
|---|---|---|
and | Returns True if both statements are true | (5 > 3) and (3 < 10) returns True |
or | Returns True if at least one of the statements is true | (5 > 3) or (3 > 10) returns True |
not | Reverse the result, returns False if the result is true | not (5 > 3) returns False |
1x = 52y = 334print("x > y and y < 10:", x > y and y < 10)5print("x > y or y > 10:", x > y or y > 10)6print("not (x > y):", not (x > y))
x > y and y < 10: True x > y or y > 10: True not (x > y): False
Identity operators are used to compare the memory locations of two objects. They check if both variables point to the same object in memory.
| Operator | Description | Example |
|---|---|---|
is | Returns True if both variables point to the same object | a is b returns True if a and b point to the same object |
is not | Returns True if both variables do not point to the same object | a is not b returns True if a and b do not point to the same object |
1a = [1, 2, 3]2b = a3c = [1, 2, 3]45print("a is b:", a is b)6print("a is c:", a is c)7print("a is not c:", a is not c)
a is b: True a is c: False a is not c: True
Membership operators are used to test if a sequence (string, list, tuple, etc.) contains a specified value.
| Operator | Description | Example |
|---|---|---|
in | Returns True if a sequence contains the specified value | 'a' in 'apple' returns True |
not in | Returns True if a sequence does not contain the specified value | 'b' not in 'apple' returns True |
1text = "Hello, world!"23print("'o' in text:", 'o' in text)4print("'z' not in text:", 'z' not in text)56numbers = [1, 2, 3, 4, 5]7print("3 in numbers:", 3 in numbers)8print("6 not in numbers:", 6 not in numbers)
'o' in text: True 'z' not in text: True 3 in numbers: True 6 not in numbers: True
Bitwise operators are used to perform operations on individual bits of binary numbers. These operators are less commonly used but can be powerful for certain tasks.
| Operator | Description | Example |
|---|---|---|
& | Bitwise AND | 5 & 3 = 1 |
| | Bitwise OR | 5 | 3 = 7 |
^ | Bitwise XOR | 5 ^ 3 = 6 |
~ | Bitwise NOT | ~5 = -6 |
<< | Bitwise Left Shift | 5 << 1 = 10 |
>> | Bitwise Right Shift | 5 >> 1 = 2 |
1a = 52b = 334print("Bitwise AND:", a & b)5print("Bitwise OR:", a | b)6print("Bitwise XOR:", a ^ b)7print("Bitwise NOT:", ~a)8print("Bitwise Left Shift:", a << 1)9print("Bitwise Right Shift:", a >> 1)
Bitwise AND: 1 Bitwise OR: 7 Bitwise XOR: 6 Bitwise NOT: -6 Bitwise Left Shift: 10 Bitwise Right Shift: 2
Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before those with lower precedence.
Here is a table of operator precedence in Python, from highest to lowest:
| Operator Type | Operators |
|---|---|
| Parentheses | () |
| Exponentiation | ** |
| Bitwise NOT | ~ |
| Unary plus and minus | +x, -x |
| Multiplication, Division, Floor Division, Modulus | *, /, //, % |
| Addition, Subtraction | +, - |
| Bitwise Shift | <<, >> |
| Bitwise AND | & |
| Bitwise XOR | ^ |
| Bitwise OR | | |
| Comparison | ==, !=, >, <, >=, <= |
| Identity | is, is not |
| Membership | in, not in |
| Logical NOT | not |
| Logical AND | and |
| Logical OR | or |
1result = 10 + 5 * 2 - 3 ** 22print("Result:", result)
Result: 14
Tip
Understanding operator precedence is crucial to ensure that your expressions are evaluated as intended. You can use parentheses () to override the default precedence and control the order of operations.
Let's create a practical example that combines several operators to perform a simple calculation and decision-making process.
1# Calculate the total cost including tax2price = 100.03tax_rate = 0.0845total_cost = price + (price * tax_rate)67# Check if the total cost is within a budget8budget = 110.0910if total_cost <= budget:11print("Within budget")12else:13print("Over budget")1415# Use bitwise operators to check permissions16read_permission = True17write_permission = False1819has_permissions = read_permission and write_permission2021print("Has read and write permissions:", has_permissions)
Within budget Has read and write permissions: False
In this tutorial, you learned about various types of operators in Python:
You also learned about operator precedence, which determines the order in which operators are evaluated in an expression. Understanding these concepts will help you write more effective and efficient Python code.
In the next tutorial, we'll explore control flow statements using the if...else statement. This will allow you to make decisions based on conditions in your programs. Stay tuned!
$ python3 practical_example.py
Within budget Has read and write permissions: False