Coding Techniques
Operators and Expressions · Study material
Digit and number tricks with // and %
// and % pull numbers apart, divmod() does both at once, and three-argument pow() computes powers modulo m without huge intermediate numbers.
n = 1234
print(n % 10, n // 10 % 10, n // 100) # last digit, tens digit, drop two digits
print(n % 2 == 0, -7 % 3) # even test; Python's % is never negative for a positive divisor
print(pow(2, 10), pow(2, 100, 1_000_007)) # pow with a modulus is fast modular exponentiation
print(max(3, 9, 4), abs(-12), round(7 / 3, 2))
hours, minutes = divmod(135, 60)
print(f"{hours}h {minutes}m")
4 3 12 True 2 1024 698635 9 12 2.33 2h 15m
Defaults with or – and its trap
name = input().strip()
display = name or "Guest" # "" is falsy → "Guest"
# Trap: 0 is falsy too, so a real 0 is replaced
discount = 0
rate = discount or 10 # 10 – probably not what you wanted
rate = 10 if discount is None else discount # explicit None check keeps 0 Testing one value against several
grade = "C"
if grade == "A" or "B": # ✘ always True: "B" is a truthy operand
pass
if grade == "A" or grade == "B": # ✔ correct but long
pass
if grade in ("A", "B"): # ✔ idiomatic
pass Operators checklist
- Use / for averages, // only for whole-number division.
- Bracket -x when raising to a power.
- Use chained comparisons for ranges.
- Use in with a tuple or set to test several values.
- Compare to None with is, everything else with ==.
- Use bitwise operators for flags and powers of two, not for logic.