🌱BeginnerPython Fundamentals
Operators and Expressions
Arithmetic, comparison, logical, and assignment operators in Python.
Overview
Operators are symbols that perform operations on values. Python provides a comprehensive set of operators organized into several categories:
**Arithmetic operators** perform math: +, -, *, /, // (floor division), % (modulo), ** (exponentiation).
**Comparison operators** compare two values and return True or False: ==, !=, <, >, <=, >=. A common beginner mistake is using = (assignment) where == (comparison) is needed.
**Logical operators** combine boolean expressions: and, or, not. Python evaluates them with short-circuit logic it stops as soon as the result is determined.
**Assignment operators** are shortcuts for common patterns: +=, -=, *=, /=, //=, **=, %= all modify a variable in place.
An **expression** is anything that produces a value from a simple literal like 42 to complex combined operations like (a + b) * c // 2. Python evaluates expressions following standard mathematical precedence (PEMDAS), which you can always override with parentheses.
Key Points
- •/ always returns float in Python 3; use // for integer (floor) division
- •% is the modulo (remainder) operator: 10 % 3 == 1
- •Comparison operators return True or False; == checks equality, = assigns
- •and/or/not are the logical operators (not &&/||/! as in C-style languages)
- •and and or short-circuit: `a and b` only evaluates b if a is truthy
- •Augmented assignment: `x += 5` is equivalent to `x = x + 5`
- •Python respects standard operator precedence; use parentheses to clarify
Examples
Arithmetic operators
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
print(10 % 3) # 1 modulo (remainder)
print(10 ** 3) # 1000 exponentiationComparison and logical operators
x = 5
print(x == 5) # True
print(x != 5) # False
print(x > 3) # True
print(x >= 10) # False
# Logical operators
print(x > 3 and x < 10) # True
print(x > 10 or x == 5) # True
print(not x == 5) # False
# Python allows chained comparisons
print(1 < x < 10) # True very Pythonic!Augmented assignment operators
score = 0
score += 10 # score = score + 10 → 10
score *= 2 # score = score * 2 → 20
score -= 5 # score = score - 5 → 15
print(score) # 15Common Mistakes
- Using = instead of == in a condition: `if x = 5:` is a SyntaxError; use `if x == 5:`
- Unexpected float result from /: if you need an integer, use // deliberately
- Confusing and/or with bitwise &/| they are different operators with different behaviour
Note
Use Python's interactive REPL to test operator precedence: try `2 + 3 * 4` (14) vs `(2 + 3) * 4` (20) to see how Python evaluates expressions.
Exercises
Write Python code to solve each exercise. Run it in your browser and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4