Python Operators and Expressions
Posted On February 1, 2023
In Python, an operator is a special symbol that performs an operation on one or more operands. For example, the addition operator + adds two operands. An expression is a combination of values, variables, and operators that produces a result.
Here are some common operators in Python:
| Operator | Description | Example | Result |
| + | Addition | 8 + 4 | 12 |
| – | Subtraction | 8 – 4 | 4 |
| * | Multiplication | 8 * 2 | 16 |
| / | Division | 8 / 2 | 4 |
| % | Modulus | 9 % 2 | 1 |
| ** | Exponentiation | 2 ** 3 | 8 |
| // | Integer Division | 5 // 2 | 2 |
Sample Code
# Addition
print(2 + 3) # Output: 5
print(2.5 + 3.5) # Output: 6.0
# Subtraction
print(5 - 2) # Output: 3
print(5.5 - 2.5) # Output: 3.0
# Multiplication
print(2 * 3) # Output: 6
print(2.5 * 3.5) # Output: 8.75
# Division
print(4 / 2) # Output: 2.0
print(4.5 / 1.5) # Output: 3.0
# Modulus (remainder)
print(5 % 2) # Output: 1
print(5.5 % 2.5) # Output: 0.5
# Exponentiation
print(2 ** 3) # Output: 8
print(2.5 ** 3.5) # Output: 14.874786781169505
# Integer division (floor division)
print(5 // 2) # Output: 2
print(5.5 // 2.5) # Output: 2.0
Expression examples
Following are some examples of python expressions:
2 + 3 * 4 # Output: 14
(2 + 3) * 4 # Output: 20
5 / 2 # Output: 2.5
5 // 2 # Output: 2 (integer division)
5 % 2 # Output: 1 (remainder)
2 ** 3 # Output: 8 (2 to the power of 3)
In Python, operator precedence determines the order in which operations are performed. For example, in the expression 2 + 3 * 4, the multiplication * has higher precedence than the addition +, so it is performed first. You can use parentheses to specify the order of operations.