Introduction
Control flow allows your program to make decisions and execute code conditionally or repeatedly. This step will guide you through if-else statements, loops (for, while), and loop control statements.
1. Conditional Statements (if-elif-else)
Conditional statements allow the program to make decisions based on conditions.
Basic if Statement
age = 18
if age >= 18:
print("You are an adult.")
if-else Statement
num = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
if-elif-else (Multiple Conditions)
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
2. Loops (for & while)
Loops allow you to execute a block of code multiple times.
For Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using range() in For Loop
for i in range(5):
print(i)
While Loop
count = 0
while count < 5:
print("Count:", count)
count += 1
3. Loop Control Statements
Break Statement (Exit Loop Early)
for i in range(10):
if i == 5:
break # Stops loop when i equals 5
print(i)
Continue Statement (Skip Current Iteration)
for i in range(5):
if i == 2:
continue # Skips when i is 2
print(i)
Pass Statement (Placeholder for Future Code)
for i in range(5):
if i == 3:
pass # Placeholder, does nothing
print(i)
4. Nested Loops & Conditionals
Loops and conditionals can be nested within each other.
Example: Nested Loops
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
Example: Nested if Statements
num = 15
if num > 10:
if num % 2 == 0:
print("Even number greater than 10")
else:
print("Odd number greater than 10")
Exercises
- Write a program that asks the user for a number and prints whether it is positive, negative, or zero.
- Write a loop that prints numbers from 1 to 10, but skips 5 using the
continue
statement. - Write a program that prints the first 10 even numbers using a
while
loop. - Create a nested loop that prints a multiplication table (1-5).
- Write a program that categorizes a given number based on multiple conditions using
if-elif-else
.
Conclusion
You have now mastered control flow in Python, including conditionals, loops, and loop control statements. The next step is to dive into functions and modular programming.