Script Valley
Python: Complete Language Course
Python Basics and SyntaxLesson 1.3

Python operators and expressions — complete guide

arithmetic operators, comparison operators, logical operators, assignment operators, operator precedence, floor division, modulo

Operators in Python

Operators work on values or variables to produce a result. Python groups them by function.

Arithmetic

print(10 + 3)   # 13  addition
print(10 - 3)   # 7   subtraction
print(10 * 3)   # 30  multiplication
print(10 / 3)   # 3.3333  true division (always float)
print(10 // 3)  # 3   floor division (truncates)
print(10 % 3)   # 1   modulo (remainder)
print(2 ** 8)   # 256 exponentiation

Comparison and Logical

x = 10
print(x > 5)    # True
print(x == 10)  # True  (== not =)
print(x != 0)   # True

print(x > 5 and x < 20)  # True
print(x < 0 or x == 10)  # True
print(not True)           # False

Operator Precedence

Python follows PEMDAS. Exponentiation binds tightest, then multiplication/division, then addition/subtraction. Comparison operators come after arithmetic. Logical operators (not, and, or) bind last. Use parentheses to make intent explicit — do not rely on memorising precedence for complex expressions.

result = 2 + 3 * 4    # 14, not 20
result = (2 + 3) * 4  # 20

Understanding operator precedence prevents subtle bugs in compound expressions. When in doubt, add parentheses to make your intent explicit — this also makes the code easier for others to read. The modulo operator is extremely useful: checking n % 2 == 0 for even numbers, cycling through a fixed-size buffer with index % buffer_size, and computing check digits. Floor division is the right tool when you need a whole number result — avoid casting the result of true division to int, since int(10 / 3) relies on truncation which behaves differently for negative numbers.

Up next

Python if else and conditional logic

Sign in to track progress