Skip to content

Operators and Flow Control

Operators let you combine and compare values; flow control decides which code runs and how often. Together they form the logic of every program.

+ add 5 + 3 → 8
- subtract 5 - 3 → 2
* multiply 5 * 3 → 15
/ divide (always float) 7 / 2 → 3.5
// integer division 7 // 2 → 3 (always rounds down)
% modulo (remainder) 7 % 2 → 1 (7 = 3×2 + remainder 1)
** exponent 2 ** 3 → 8 (2 to the power of 3)
x += 3 → x = x + 3
x -= 3 → x = x - 3
x *= 3 → x = x * 3
x /= 3 → x = x / 3
== equal to 5 == 5 → True
!= not equal to 5 != 3 → True
< less than 3 < 5 → True
> greater than 5 > 3 → True
<= less than or equal 5 <= 5 → True
>= greater than or equal 5 >= 6 → False
and both True? True and False → False
or at least one? True or False → True
not invert not True → False
** → * / // % → + - → comparison → not → and → or

So 2 + 3 * 4 = 2 + 12 = 14 (not 20).

in 'top' in 'desktop' → True
+ 'hi' + ' ' + 'there' → 'hi there' (concatenation)
* 'ha' * 3 → 'hahaha' (repetition)
[] lst[0], s[2:5] (indexing / slicing)
print(17 // 5) # expect: ?
print(17 % 5) # expect: ?
print(2 ** 10) # expect: ?
print(10 / 3) # expect: ?
print(10 // 3) # expect: ?
print(-7 // 2) # expect: ? (note: floor = rounds down)
print(8 + 2 * 2) # expect: ? (precedence!)
print((8 + 2) * 2) # expect: ?
score = 75
if score >= 90:
print("A") # only if score >= 90
elif score >= 80:
print("B") # only if score 80-89
elif score >= 70:
print("C") # only if score 70-79 ← this one runs
else:
print("F") # all other cases

Important: as soon as one condition is True, the rest are not checked. So score = 95 prints just "A", not "A B C".

Common gotcha: With a chain of overlapping conditions, the first match wins and the rest are skipped.

Use it when you know how many times you want to repeat:

for i in range(5): # i = 0, 1, 2, 3, 4
print(i)
for letter in "hi": # letter = 'h', 'i'
print(letter)
for item in [10, 20, 30]: # item = 10, 20, 30
print(item)

range() variants:

range(5) # 0, 1, 2, 3, 4
range(2, 5) # 2, 3, 4
range(0, 10, 2) # 0, 2, 4, 6, 8 (step of 2)
range(10, 0, -1) # 10, 9, 8, ..., 1 (counting down)

Use it when you do not know in advance how many times:

x = 0
while x < 5:
print(x)
x += 1 # do not forget this, or you get an infinite loop
for i in range(10):
if i == 5:
break # STOP the whole loop
if i == 3:
continue # skip 3, move on to 4
print(i)
# Output: 0, 1, 2, 4 (3 skipped, stops at 5)

Predict the output before you press Enter:

for i in range(1, 10, 3):
print(i, end=" ")
# expect: ?
x = 100
while x > 1:
x = x // 2
print(x, end=" ")
# expect: ?

In Python, True equals 1 and False equals 0, so they work in arithmetic:

True + 2 # → 3 (True = 1)
False + 2 # → 2 (False = 0)
True * 10 # → 10

This is handy for counting True results, for example sum(x > 0 for x in numbers).