Python Course in 4 to 6 Weeks – Lesson 7: Loops in Python (for, while)

🔁 Python Course in 4 to 6 Weeks – Lesson 7: Loops in Python (for, while)

Welcome to Lesson 7 of the Python Course in 4 to 6 Weeks! In this lesson, you'll learn how to automate repetitive actions using Python's two main types of loops: for and while. Loops are essential for reducing code repetition and handling data collections.



✅ What You'll Learn

  • When and why to use loops
  • The for loop structure and syntax
  • The while loop and control flow
  • Loop control keywords: break, continue, pass
  • Real-world examples and challenges

🔁 The for Loop

Used to iterate over a sequence (like a list, tuple, or string):

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

🔄 The while Loop

Repeats a block of code while a condition is True:

count = 0
while count < 5:
    print("Count:", count)
    count += 1

⚙️ Loop Control Statements

  • break: Exit the loop completely
  • continue: Skip to the next iteration
  • pass: Do nothing (used as a placeholder)
for i in range(5):
    if i == 3:
        continue  # Skips printing 3
    print(i)

📏 The range() Function

Commonly used with for loops to repeat actions:

for i in range(1, 6):
    print("Hello", i)

⚠️ Common Mistakes

  • ❌ Infinite loops with while by forgetting to update the condition
  • ❌ Using incorrect indentation inside loop blocks
  • ❌ Off-by-one errors in range()

🧪 Practice Challenge

Create a Python file named multiples_finder.py that:

  • Asks the user for a number
  • Prints all multiples of that number up to 100 using a loop

📥 Tools You'll Need

📌 Final Words

Loops are the key to efficient and dynamic programs. With for and while, you can repeat tasks, process data, and build interactive programs. Up next, we’ll explore one of Python’s most flexible data structures: lists and tuples.

🔗 Coming Next:

Lesson 8: Lists & Tuples – Working with Sequences 📦

Post a Comment