๐ฏ Lesson Objective
To understand how to repeat tasks using loops in Python efficiently.
You will learn about the for loop, while loop, nested loops, and control statements like break and continue.
๐ง 1. What Are Loops?
Loops allow you to execute a block of code repeatedly until a certain condition is met.
They are used when you want to perform the same task multiple times โ for example, printing numbers, iterating through a list, or processing data.
๐ 2. Types of Loops in Python
Python supports two main types of loops:
- for loop โ used for iterating over a sequence (list, tuple, string, etc.)
- while loop โ runs as long as a condition remains True
โ๏ธ 3. for Loop Syntax
for variable in sequence:
# code block
Example:
for i in range(5):
print("Hello Python")
Output:
Hello Python
Hello Python
Hello Python
Hello Python
Hello Python
๐ 4. Using range() Function
The range() function generates a sequence of numbers.
It can take 1, 2, or 3 arguments: range(start, stop, step)
Example:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
๐ 5. Looping Through Lists and Strings
You can loop through any iterable (like a list or string).
Example 1: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Example 2: Loop through a string
for letter in "PYTHON":
print(letter)
โณ 6. The while Loop
A while loop runs until its condition becomes False.
Syntax:
while condition:
# code block
Example:
count = 1
while count <= 5:
print("Count:", count)
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
โ ๏ธ 7. Infinite Loops
If the condition in a while loop never becomes False, it runs forever.
while True:
print("This will run forever!")
โ Use Ctrl + C to stop infinite loops manually.
๐งฉ 8. Loop Control Statements
Python provides special keywords to control loop behavior.
break โ Exit the loop early
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
continue โ Skip the current iteration
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
pass โ Placeholder for future code
for i in range(3):
pass # no action taken now
๐ 9. Nested Loops
You can place one loop inside another.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
๐ 10. Real-Life Example: Multiplication Table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Output (for input 5):
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
๐ง 11. Practice Ideas
- Print numbers from 1 to 20 using both
forandwhileloops. - Display all even numbers between 1 and 50.
- Create a program that reverses a string using a loop.
- Use a loop to count vowels in a given sentence.
- Generate a simple pattern like:
* ** *** **** *****

Leave a Reply