Programs (Last-Minute Revision Notes 2026) (Part 2)
Loops in Python
🔹 Introduction to Loops
In programming, loops are used to repeat a block of code multiple times.
Real-life examples
Studying daily for 7 days
Printing numbers from 1 to 100
Repeating an action until a condition is met
👉 Instead of writing the same code again and again, we use loops.
🔹 Types of Loops in Python
1. for loop
2. while loop
🔹 The for Loop
Used when you know how many times you want to repeat something.
Syntax:
for variable in range(start, stop, step):
# code
🔥 Example 1: Print Numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
🔥 Example 2: Print Even Numbers
for i in range(2, 11, 2):
print(i)
1
,Output:
2
4
6
8
10
🔹 The while Loop
Used when you want to repeat until a condition becomes false.
Syntax:
while condition:
# code
🔥 Example 3: Print Numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
🔹 break Statement
Used to exit the loop immediately.
🔥 Example 4
for i in range(1, 10):
if i == 5:
break
print(i)
👉 Stops when i = 5
Output:
1
2
3
4
2
,🔹 continue Statement
Used to skip one iteration.
🔥 Example 5
for i in range(1, 6):
if i == 3:
continue
print(i)
👉 Skips number 3
Output:
1
2
4
5
🔹 Nested Loops
A loop inside another loop.
🔥 Example 6
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
🔥 Example 7: Print Stars Pattern
for i in range(5):
print("*" * (i + 1))
Output:
*
**
***
3
, ****
*****
🔥 Example 8: Reverse Counting
for i in range(10, 0, -1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
🔥 Example 9: Multiplication Table
num=int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)
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
🔥 Example 10: Sum of First N Numbers
n=int(input("Enter value of n: "))
total = 0
for i in range(1, n + 1):
total += i
print("Sum is:", total)
Output:
Enter value of n: 5
Sum is: 15
4