π Overview
Loops allow you to repeat actions automatically in Python. Instead of writing the same code again and again, loops help you run blocks of code multiple times until a condition is met.
π― What Youβll Learn
-
What loops are and why theyβre useful
-
How to use
for
andwhile
loops -
How to use
break
andcontinue
for control -
Practical examples using both loop types
π 1. What is a Loop?
A loop lets your program repeat a block of code until a condition is met or for a number of times.
π’ 2. for
Loops (Counted Repetition)
Used to loop through a sequence like a list, string, or a range of numbers.
π Output:
π‘ Looping with range(start, stop, step)
Output:
π 3. while
Loops (Conditional Repetition)
A while
loop continues as long as a condition is true.
βοΈ 4. Loop Control Statements
πΉ break
Stops the loop completely.
πΉ continue
Skips the current loop iteration.
π― 5. Practice Task
Write a program that:
-
Asks the user for a number
n
-
Prints all numbers from 1 to
n
π§ Mini Challenge
Print all even numbers between 1 and 20 using a loop.
β Summary
-
Use
for
loops when you know how many times to repeat -
Use
while
loops when you loop based on a condition -
Use
break
to exit early andcontinue
to skip iterations
βοΈ Next Lesson Preview
β Functions and Parameters in Python