๐น 1. What is a Loop?
A loop is used to repeat a block of code multiple times.
๐ Without loops โ code becomes long
๐ With loops โ code becomes short & clean
Python has mainly two loops:
forloopwhileloop
๐น 2. for Loop
A for loop is used when number of repetitions is known.
Example 1: Printing Numbers
for i in range(5):
print(i)
Output
0
1
2
3
4
๐ Explanation
range(5)generates numbers from0to4- Loop runs 5 times
Example 2: Printing Numbers from 1 to 5
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
Example 3: Printing Names
names = ["Sameer", "Ayesha", "Saddam", "Chandini"]
for name in names:
print(name)
Output
Sameer
Ayesha
Saddam
Chandini
๐ Explanation
- Loop runs once for each item in the list
๐น 3. range() Function
| Syntax | Meaning |
|---|---|
range(stop) | 0 to stop-1 |
range(start, stop) | start to stop-1 |
range(start, stop, step) | step increment |
Example 4: Step Value
for i in range(1, 11, 2):
print(i)
Output
1
3
5
7
9
๐น 4. while Loop
A while loop runs as long as a condition is true.
Example 5: Print Numbers Using while
i = 1
while i <= 5:
print(i)
i += 1
Output
1
2
3
4
5
๐ Explanation
- Condition checked before every iteration
- If condition becomes
False, loop stops
๐น 5. Infinite Loop (IMPORTANT)
while True:
print("Hello")
โ This loop never stops unless manually interrupted.
๐น 6. break Statement
Used to stop the loop immediately.
Example 6: Stop Loop When Condition Met
for i in range(1, 10):
if i == 5:
break
print(i)
Output
1
2
3
4
๐น 7. continue Statement
Used to skip the current iteration.
Example 7: Skip a Number
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1
2
4
5
๐น 8. else with Loops
Example 8: Loop with else
for i in range(3):
print(i)
else:
print("Loop completed")
Output
0
1
2
Loop completed
๐ Explanation
elseruns when loop ends normally- It does NOT run if
breakis used
๐น 9. Nested Loops (Loop inside Loop)
Example 9: Number Pattern
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
Example 10
number = int(input("Enter a number: "))
for i in range(1, 11):
print(number, "x", i, "=", number * i)
Sample Output
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
๐น 11. Common Mistakes (IMPORTANT)
โ Forgetting to update condition in while loop
โ Wrong indentation
โ Infinite loops accidentally
โ Using break incorrectly
๐ง Final Summary
โ for loop โ fixed number of times
โ while loop โ condition-based
โ range() controls repetition
โ break stops loop
โ continue skips iteration
โ Nested loops handle complex logic

Leave a Reply