Operators & Expressions
Arithmetic, comparison, logical, and string operators
Skills taught: python.operators, python.f-strings, python.expressions
Arithmetic operators
# Basic arithmetic
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333... (always float)
print(10 // 3) # 3 (floor division — integer result)
print(10 % 3) # 1 (modulo — remainder)
print(2 ** 10) # 1024 (power)
# Order of operations
print(2 + 3 * 4) # 14 (multiplication first)
print((2 + 3) * 4) # 20 (brackets first)
# Augmented assignment
x = 10
x += 5 # x = x + 5 → 15
x *= 2 # x = x * 2 → 30
print(x) # 30
Comparison & logical operators
# Comparison — returns True or False
print(5 == 5) # True
print(5 != 3) # True
print(5 > 3) # True
print(5 < 3) # False
print(5 >= 5) # True
print(5 <= 4) # False
# Chained comparisons (unique to Python!)
age = 25
print(18 <= age < 65) # True — works like math!
# Logical operators
print(True and True) # True
print(True and False) # False
print(True or False) # True
print(not True) # False
# Combining
x = 7
print(x > 0 and x < 10) # True
print(x < 0 or x > 5) # True
print(not (x == 7)) # False
f-strings — formatted string literals
name = 'Prashant'
age = 28
price = 9.99
# f-string: prefix with f, put expressions in {}
print(f'Hello, {name}!')
# → Hello, Prashant!
print(f'{name} is {age} years old')
# → Prashant is 28 years old
# Expressions inside {}
print(f'Next year: {age + 1}')
# → Next year: 29
# Format numbers
print(f'Price: ₹{price:.2f}') # 2 decimal places
# → Price: ₹9.99
print(f'{1000000:,}') # thousands separator
# → 1,000,000
# String operators
greeting = 'Hello' + ', ' + 'World!' # concatenation
line = '-' * 20 # repeat
print(greeting) # Hello, World!
print(line) # --------------------
Frequently Asked Questions
Why does 0.1 + 0.2 not equal 0.3 in Python?
Floating-point numbers use binary representation (IEEE 754), and 0.1 and 0.2 can't be represented exactly in binary — similar to how 1/3 can't be exactly represented in decimal. Use round(0.1 + 0.2, 1) == 0.3, or the decimal module for financial precision: from decimal import Decimal.
What is the difference between == and is?
== compares values (5 == 5.0 is True). is compares identity — whether two variables point to the exact same object in memory (a is b). Use == for value comparison. Use is only for None: if x is None: ...