Arithmetic Operators
Python supports the following arithmetic operators:
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus)**
(Exponentiation)//
(Floor Division)
x = 10
y = 3
print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.3333333333333335
print(x % y) # Output: 1
print(x ** y) # Output: 1000
print(x // y) # Output: 3
Assignment Operators
Python provides several assignment operators to simplify value assignment:
=
(Simple Assignment)+=
(Addition Assignment)-=
(Subtraction Assignment)*=
(Multiplication Assignment)/=
(Division Assignment)%=
(Modulus Assignment)**=
(Exponentiation Assignment)//=
(Floor Division Assignment)
x = 10
x += 5 # Same as x = x + 5
print(x) # Output: 15
y = 20
y -= 3 # Same as y = y - 3
print(y) # Output: 17
Comparison Operators
Comparison operators are used to compare values and return a boolean result (True
or False
):
==
(Equal to)!=
(Not equal to)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)
x = 10
y = 5
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
Logical Operators
Logical operators are used to combine conditional statements:
and
(Logical AND)or
(Logical OR)not
(Logical NOT)
x = 10
y = 5
z = 20
print(x > y and x < z) # Output: True
print(x > y or x > z) # Output: True
print(not (x > z)) # Output: True
Bitwise Operators
Bitwise operators are used to perform operations on individual bits:
&
(Bitwise AND)|
(Bitwise OR)^
(Bitwise XOR)~
(Bitwise NOT)<<
(Left Shift)>>
(Right Shift)
x = 10 # Binary: 1010
y = 7 # Binary: 0111
print(x & y) # Output: 2 (Binary: 0010)
print(x | y) # Output: 15 (Binary: 1111)
print(x ^ y) # Output: 13 (Binary: 1101)
print(~x) # Output: -11 (Binary: -1011)
print(x << 2) # Output: 40 (Binary: 101000)
print(y >> 1) # Output: 3 (Binary: 11)
Operator Precedence
When multiple operators are used in an expression, the order of evaluation follows the operator precedence rules. Here's the order of precedence from highest to lowest:
- Parentheses
- Exponentiation
- Unary operators (e.g.,
+
,-
,~
) - Multiplication, Division, Modulus, Floor Division
- Addition, Subtraction
- Bitwise operators
- Comparison operators
- Boolean operators (
not
,and
,or
) - Assignment operators
Expressions
An expression is a combination of operators, values, and variables that evaluate to a single value. Expressions can be used in statements, function calls, and other contexts where a value is expected.
result = (10 + 3) * 2 # result = 26
is_positive = x > 0 # is_positive is a boolean value