Skip to content

Operators and Control Flow

>Operators and Control Flow — cheat sheet

Use expressions, decisions, and loops to make your program calculate and choose what happens next.

Arithmetic and assignment

total = 17
people = 4
print(total // people)
// keeps the whole-number result of division.
print(17 % 4)
% gives the remainder after division.
print(2 ** 5)
** raises a number to a power.
score = 8
score += 4
Update a value by adding and assigning.

Tests and conditions

print(5 >= 5)
Comparisons produce True or False.
print(age >= 18 and has_ticket)
and needs both conditions to be true.
print("py" in "python")
in checks whether a value appears in a collection.
value = None
print(value is None)
Use is to check whether a value is None.

Input, output, and match

name = "Mina"
points = 42
print(f"{name} has {points} points.")
An f-string places values or expressions inside text.
price = 3.5
print(f"${price:.2f}")
:.2f shows a number with two decimal places.
entered_age = "12"
age = int(entered_age)
input returns text, so convert numeric input before calculating.
match "start":
    case "start":
        print("Starting")
    case _:
        print("Unknown")
match-case chooses code for fixed values; _ is the fallback.

if, elif, and else

if score >= 90:
    print("A")
Run an indented block only when its condition is true.
if age < 18:
    print("Junior")
else:
    print("Adult")
else is the fallback when if is false.
if score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif checks another condition after if.
label = "has text" if "go" else "empty"
A conditional expression makes a short two-way choice.

for loops

for letter in "cat":
    print(letter)
Visit each character or item in order.
for number in range(2, 8, 2):
    print(number)
range starts, stops before, and steps through numbers.
for index, item in enumerate(["pear", "plum"], start=1):
    print(index, item)
enumerate supplies both a position and an item.
for name, score in zip(["Ana", "Bo"], [9, 7]):
    print(name, score)
zip pairs values from two collections.

while and loop control

count = 1
while count <= 3:
    count += 1
A while loop repeats while its condition stays true.
for number in range(5):
    if number == 3:
        break
break exits the nearest loop early.
for number in range(5):
    if number == 3:
        continue
    print(number)
continue skips the rest of one loop repeat.
if True:
    pass
pass is a placeholder that does nothing.
All cheat sheets