About Lesson
๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Understand the need for loops in programming
-
Use
for
andwhile
loops to repeat actions -
Apply
range()
in loops -
Control repetition based on conditions
๐ Lesson Content
๐น Why Use Loops?
Loops allow you to repeat a block of code multiple times, saving time and avoiding repetition.
Instead of writing:
You can write:
๐ธ The for
Loop
The for
loop is used to iterate over a sequence (like a list, string, or range of numbers).
Syntax:
โ
Example with range()
:
Output:
range(start, stop)
generates numbers fromstart
tostop - 1
๐ธ The while
Loop
A while
loop runs as long as a condition is True
.
Syntax:
โ Example:
โ ๏ธ Be Careful: Infinite Loops!
โ Make sure your loop has a condition that becomes False
, or use break
to stop it.
๐ Loop Use Cases
Loop Type | Best Used When |
---|---|
for |
You know how many times to repeat |
while |
You want to loop until a condition is met |
ย
๐ง Mini Exercise
๐ Assignment
Create a program using:
-
A
for
loop to print numbers 1 to 10 -
A
while
loop to print numbers from 10 down to 1