Lesson: Loops in Python ( by prompt AI )

 

Lesson: Loops in Python

[introduction]

Hello again! Today we’re exploring loops, one of the most powerful tools in Python. Loops allow you to repeat actions without writing the same code over and over. By the end of this lesson, you’ll understand both major loop types in Python: for loops and while loops.


[concept_explanation]

A loop is a programming construct that repeats a block of code multiple times.
Python mainly uses two types of loops:

1. for Loop

Used when you want to repeat something a specific number of times, or when iterating over a collection (like a list, string, or range of numbers).

Key points:

  • It automatically goes through each item in a sequence.

  • You don’t manually control the loop counter (Python does it for you).

2. while Loop

Used when you want to repeat something as long as a condition remains true.

Key points:

  • You control when the loop stops.

  • You must update the condition inside the loop to avoid infinite loops.

Loops help automate repetition, reduce errors, and make code efficient and clean.


[python_examples]

Example of a for loop

for i in range(5): print("Hello!", i)

Example of iterating over a list

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit)

Example of a while loop

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

[analogy]

Think of a for loop like a playlist: you automatically move through each song one by one until the playlist ends.
A while loop is like reading a book until you’re tired — you keep going as long as your condition is true.


[practice_task]

Try creating these loops:

  1. Write a for loop that prints the numbers from 1 to 10.

  2. Write a while loop that counts down from 5 to 1.

  3. Write a for loop that prints each letter of your name.


[quiz]

  1. Which loop is best when you know the exact number of repetitions?

  2. True or False: A while loop needs its condition to eventually become false.

  3. What is the output of this code?

for i in range(3): print("Hi")

[common_mistakes]

  • Forgetting to update the condition inside a while loop → causes infinite loops.

  • Misusing indentation — loops rely heavily on correct indentation.

  • Using range() incorrectly (e.g., expecting it to include the end value).

  • Iterating incorrectly over lists by indexing manually when it’s unnecessary.


[extra_notes]

You can use break and continue inside loops:

  • break stops the loop immediately.

  • continue skips to the next iteration.
    These are useful when handling specific conditions inside loops.

Comments

Popular posts from this blog

Ecommerce website

Yes, Python is an object-oriented programming (OOP) language, but it is also a multi-paradigm language

Your task is to find the missing number.