Loops (for, while)
[Link] Loop and range()
Definition
A for loop is used to repeat a block of code for a fixed number of times.
The range() function is commonly used with for loops to generate a sequence of numbers.
Syntax
for variable in range(start, stop, step):
# code to execute each time
• start → where to begin (default = 0)
• stop → where to end (loop stops before this number)
• step → how much to increase each time (default = 1)
Example 1
for i in range(5):
print(i)
Output:
0
1
2
3
4
(loops from 0 to 4)
Example 2
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
Starts at 2, ends before 11, step = 2.
[Link] Loop
Definition
A while loop executes a block of code as long as a condition is True.
If the condition becomes False, the loop stops.
Syntax
while condition:
# code to execute
Example 1
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Example 2
count = 5
while count > 0:
print("Countdown:", count)
count -= 1
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
[Link], continue, pass
1. break Statement
Definition:
Used to exit the loop immediately, even if the condition is still true.
Syntax:
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
Loop stops when i becomes 3.
2. continue Statement
Definition:
Skips the rest of the loop body and goes to the next iteration.
Syntax:
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
Skips printing 2.
3. pass Statement
Definition:
A placeholder statement — does nothing.
Used when a statement is required syntactically but you don’t want to execute any code.
Syntax:
for i in range(3):
pass
print("Loop finished.")
Output:
Loop finished.
PRACTICE PROGRAMS
Number Pattern
Example 1: Increasing Triangle
for i in range(1, 6):
for j in range(1, i + 1):
print("*", end="")
print() Output:
*
**
***
****
*****
Example 2: Number Triangle
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end="")
print()
Output:
1
12
123
1234
12345
Factorial of a Number
Definition:
The factorial of n (written as n!) is the product of all positive integers up to n.
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Example 1: Using for loop
num = 5
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial of", num, "is", fact)
Output:
Factorial of 5 is 120
num = 4
fact = 1
i=1
while i <= num:
fact *= i
i += 1
print("Factorial of", num, "is", fact)
Output:
Factorial of 4 is 2
Sum of Digits
Definition:
To find the sum of digits, repeatedly extract each digit and add them up.
Example 1: Using while loop
num = 1234
sum_digits = 0
while num > 0:
digit = num % 10
sum_digits += digit
num //= 10
print("Sum of digits:", sum_digits)
Output:
Sum of digits: 10
Example 2: Using string conversion
num = 567
sum_digits = sum(int(digit) for digit in str(num))
print("Sum of digits:", sum_digits)
Output:
Sum of digits: 18