Python Tutorial

Control Flow & Loops

Control flow lets your program make decisions and repeat work.

if / elif / else

temperature = 28

if temperature > 30:
    print("It's hot")
elif temperature > 20:
    print("It's warm")
else:
    print("It's cool")

for loops

for loops iterate over a sequence, such as a list or the output of range().

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

for i in range(3):
    print(f"Count: {i}")

while loops

A while loop repeats as long as a condition stays true.

count = 0

while count < 3:
    print(f"Count is {count}")
    count += 1

break and continue

for number in range(10):
    if number == 5:
        break       # stop the loop entirely
    if number % 2 == 0:
        continue    # skip to the next iteration
    print(number)

Next, package up reusable logic with functions.