Control Flow if-elif-else, for loops, while loops, break, continue, pass

Python Basics: Control Flow

Python Basics: Control Flow

Master decision-making and loops to create dynamic programs!

1. if-elif-else: Make Decisions

Control flow lets your program decide what to do based on conditions.

Syntax & Examples


# Grade Checker  
score = 85  

if score >= 90:  
    print("A")  
elif score >= 80:  
    print("B")  # This line runs!  
elif score >= 70:  
    print("C")  
else:  
    print("Needs improvement")  

            

Output:


B  

            

Key Rules:

  • if is mandatory; elif/else are optional.
  • Conditions are checked top to bottom.
  • Indentation (4 spaces) defines code blocks.

2. for Loops: Iterate Over Sequences

Use for loops to repeat code for each item in a list, string, or range.

Looping Through Lists


fruits = ["apple", "banana", "cherry"]  
for fruit in fruits:  
    print(f"I love {fruit}!")  

            

Output:


I love apple!  
I love banana!  
I love cherry!  

            

Using range()


# Print numbers 1 to 5  
for num in range(1, 6):  
    print(num)  

            

Output:


1  
2  
3  
4  
5  

            

Real-World Use:

  • Process data in batches.
  • Generate patterns (e.g., multiplication tables).

3. while Loops: Repeat Until a Condition Fails

Run code as long as a condition is true.

Countdown Timer


count = 5  
while count > 0:  
    print(count)  
    count -= 1  # Decrease count by 1 each time  
print("Blastoff! 🚀")  

            

Output:


5  
4  
3  
2  
1  
Blastoff! 🚀  

            

⚠️ Avoid Infinite Loops:


# ❌ Bad Example (Never stops!)  
# while True:  
#     print("Looping forever!")  

            

4. break, continue, pass

break: Exit the Loop Early


# Stop when "cherry" is found  
fruits = ["apple", "banana", "cherry", "date"]  
for fruit in fruits:  
    if fruit == "cherry":  
        break  
    print(fruit)  

            

Output:


apple  
banana  

            

continue: Skip to the Next Iteration


# Skip even numbers  
for num in range(1, 6):  
    if num % 2 == 0:  
        continue  
    print(num)  # Prints 1, 3, 5  

            

pass: Do Nothing (Placeholder)


# Use pass as a temporary placeholder  
for num in range(5):  
    pass  # Add logic later  

            

Real-World Project: Number Guessing Game


import random  

secret_num = random.randint(1, 10)  
attempts = 3  

while attempts > 0:  
    guess = int(input("Guess a number (1-10): "))  

    if guess == secret_num:  
        print("You won! 🎉")  
        break  
    elif guess < secret_num:  
        print("Too low!")  
    else:  
        print("Too high!")  

    attempts -= 1  

if attempts == 0:  
    print(f"Out of tries! The number was {secret_num}.")  

            

Common Mistakes

  • ❌ Forgetting the colon : after if, elif, else, for, or while.
  • ❌ Mixing tabs and spaces for indentation.
  • ❌ Infinite loops (always test exit conditions!).

Key Takeaways

  • if-elif-else: Make decisions based on conditions.
  • for loops: Iterate over sequences (lists, strings, ranges).
  • while loops: Repeat code until a condition is false.
  • break/continue: Control loop execution flow.
  • pass: Use as a placeholder for future code.

Practice Quiz

What does this code output?


for i in range(3):  
    if i == 1:  
        continue  
    print(i)  

            

Answer:


0  
2  

            

Fun Activity: Build a Chatbot!

Use if-else and loops to create a simple chatbot:


while True:  
    user_input = input("You: ")  

    if user_input.lower() == "bye":  
        print("Bot: Goodbye! 👋")  
        break  
    elif "happy" in user_input:  
        print("Bot: 😊")  
    else:  
        print("Bot: Tell me more!")  

            

What’s Next?

Learn about functions to organize your code into reusable blocks!

Post a Comment

Previous Post Next Post