9. Control Flow: If Statements and Loops
What Is Control Flow?
Control flow determines **how your code executes** depending on conditions. Instead of running everything top to bottom, you can add decisions and repeat actions using loops.
If Statements
If statements let your code make decisions based on conditions using `if`, `elif`, and `else`.
age = 18
if age >= 18:
print("You are an adult")
elif age > 12:
print("You are a teenager")
else:
print("You are a child")Comparison Operators
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
For Loops
`for` loops let you repeat code for each item in a sequence like a list or a string.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)While Loops
`while` loops run as long as a condition is true. Be careful to avoid infinite loops!
count = 1
while count <= 5:
print("Count is", count)
count += 1Break and Continue
`break` stops a loop early, while `continue` skips to the next iteration.
for num in range(1, 10):
if num == 5:
break # stops the loop
print(num)
for num in range(1, 10):
if num == 5:
continue # skips 5
print(num)Real World Example
Let’s check if a password meets a length requirement. This is something real apps do during signup.
password = "mypassword123"
if len(password) < 8:
print("Password too short")
else:
print("Password accepted")Mini Exercise
Write a loop that prints all even numbers between 1 and 20. Then write an if statement that checks if a number is positive, negative, or zero.