🐍 Python Tutorial: Control Flow
Control flow allows your program to make decisions and repeat actions. In this section, you’ll learn how to use if statements, for loops, and while loops to control what your program does and when.
1. Conditional Statements (if, elif, else)
Python uses if statements to run code only if a condition is true.
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")You can use elif (short for "else if") to test multiple conditions:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Keep studying!")2. For Loops
A for loop repeats a block of code a specific number of times. Use it to iterate over a sequence like a list or range of numbers:
# Print numbers from 0 to 4
for i in range(5):
print(i)You can also use a for loop to iterate over items in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)3. While Loops
A while loop keeps running as long as a condition is True. Use it when you don't know ahead of time how many times to repeat.
count = 0
while count < 3:
print("Count is", count)
count += 1Be careful not to create an infinite loop — always make sure your loop has a way to end!