๐ Lesson 5: Python Control Flow – If/Else, Elif & Loops
Welcome to Lesson 5! Today we learn how to make decisions in code and repeat actions automatically. These skills allow you to build smart, interactive programs.
⭐ What You Will Learn in This Lesson
- How to make decisions using if, else, and elif
- How to repeat actions with loops
- When and why control flow is important in Python programs
- How to write clean, logical, and interactive programs
⚡ What Is Control Flow?
Control flow decides what your program should do next depending on certain conditions. There are three important parts:
- If/Else – make decisions
- Elif – multiple conditions
- Loops – repeat actions
๐งฉ 1. If Statements
Use if to run code only when a condition is true:
age = 18
if age >= 18:
print("You are an adult!")
๐งฉ 2. If–Else
else runs when the if condition is NOT true:
age = 15
if age >= 18:
print("Adult")
else:
print("Minor")
๐งฉ 3. Elif (Else If)
Use elif to check multiple conditions:
marks = 85
if marks >= 90:
print("A grade")
elif marks >= 80:
print("B grade")
elif marks >= 70:
print("C grade")
else:
print("Fail")
๐ 4. While Loop
Repeats the code as long as the condition is true:
count = 1
while count <= 5:
print("Number:", count)
count += 1
๐ 5. For Loop
Used to loop through items or a range of numbers:
for i in range(1, 6):
print("Number:", i)
๐ฏ Why Do We Use Loops?
Loops help you:
- Repeat actions
- Process lists and data
- Build automation scripts
- Save time and reduce repetitive code
❌ Common Mistakes
- Forgetting to update the loop variable in a while loop (infinite loop)
- Confusing if, elif, and else order
- Indentation errors inside loops or if statements
❓ Frequently Asked Questions (FAQ)
1. Can I have multiple elif statements?
Yes, Python allows as many elif conditions as needed.
2. What happens if a while loop condition never becomes false?
You will create an infinite loop. Always make sure the condition will eventually become false.
3. Can for loops be used with lists?
Yes, for loops can iterate over numbers, lists, strings, and other collections.
๐งช Practice
- Create a program that checks whether a number is:
- Positive
- Negative
- Zero
- Create a loop that prints numbers from 1 to 20.
- Ask the user for a number and print its multiplication table (1 to 10).
๐ What’s Next?
In the next lesson, you’ll learn about:
- Python functions
- How to create reusable code
- Parameters and return values
Comments
Post a Comment