🐍 Python

Control Flow

Lesson 3 of 5 ~7 min

Control flow lets your programs make decisions and repeat actions. Python provides if/elif/else for conditionals, and for and while for loops.

Conditionals

Editor
Python
Output

Try it

Change the temperature value and see which branch executes. Then try modifying the range() values in the loop.

Comparison operators

==      # Equal to
!=      # Not equal to
>       # Greater than
<       # Less than
>=      # Greater than or equal to
<=      # Less than or equal to

Logical operators

and     # Both conditions must be true
or      # At least one condition must be true
not     # Reverses the boolean value

For loops

Use for to iterate over a sequence — a range, a list, a string, or anything iterable:

# Loop with range
for i in range(5):      # 0, 1, 2, 3, 4
    print(i)

# Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Loop with enumerate (index + value)
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

While loops

Use while to repeat code as long as a condition is true:

count = 0
while count < 5:
    print(count)
    count += 1

# break and continue
for i in range(10):
    if i == 3:
        continue    # Skip 3
    if i == 7:
        break       # Stop at 7
    print(i)

Quiz

What keyword starts an else-if chain in Python?
Challenge

Write a for loop that prints only the even numbers from 1 to 10. Hint: use the modulo operator %.