Expressions and Operations
An expression is any piece of code that produces a value. When you write 10 + 5, Python evaluates it and produces 15. Expressions are how programs calculate, combine, and transform data.
Arithmetic Operations
Python supports standard math operations:
print(10 + 5) # Addition: 15
print(10 - 5) # Subtraction: 5
print(10 * 5) # Multiplication: 50
print(10 / 5) # Division: 2.0
Notice that division always returns a float, even when the result is a whole number.
Additional Math Operators
Python includes operators beyond basic arithmetic:
print(10 // 3) # Floor division: 3 (rounds down)
print(10 % 3) # Modulo: 1 (remainder after division)
print(2 ** 3) # Exponent: 8 (2 to the power of 3)
The modulo operator (%) is surprisingly useful – it tells you if a number divides evenly, helps with cycling through values, and more.
Operator Precedence
Python follows standard math rules – multiplication and division happen before addition and subtraction:
result = 10 + 5 * 2
print(result) # 20, not 30
Python multiplies 5 * 2 first (getting 10), then adds 10. Use parentheses to control order:
result = (10 + 5) * 2
print(result) # 30
When in doubt, add parentheses. They make your intentions clear.
String Operations
Strings have their own operators. The + operator concatenates (joins) strings:
greeting = "Hello" + " " + "World"
print(greeting) # Hello World
The * operator repeats strings:
laugh = "Ha" * 3
print(laugh) # HaHaHa
separator = "-" * 20
print(separator) # --------------------
Combining Variables and Operations
Expressions can include variables:
price = 100
tax_rate = 0.08
total = price + (price * tax_rate)
print(total) # 108.0
You can also update a variable using its current value:
count = 10
count = count + 1 # Now count is 11
Python evaluates the right side first, then assigns the result.
Shorthand Operators
Updating variables is so common that Python has shortcuts:
count = 10
count += 1 # Same as: count = count + 1
count -= 5 # Same as: count = count - 5
count *= 2 # Same as: count = count * 2
These make code more concise once you're comfortable with them.