Sometimes we need to repeat a task multiple times.
Examples:
- Print numbers from 1 to 10
- Print a message 5 times
- Check numbers one by one
- Process multiple inputs
Instead of writing the same code again and again, we use loops.
Loops allow us to execute a block of code repeatedly.
There are two main loops in Python:
forloopwhileloop
The for loop is mainly used when we know how many times we want to repeat something.
range() is commonly used with for loop.
for i in range(1, 6):
print(i)Output:
1
2
3
4
5
Important:
- Start value is included
- End value is excluded
range(stop)
for i in range(5):
print(i)Output:
0
1
2
3
4
range(start, stop)
for i in range(2, 6):
print(i)range(start, stop, step)
for i in range(1, 10, 2):
print(i)Output:
1
3
5
7
9
text = "Python"
for ch in text:
print(ch)This prints each character one by one.
The while loop runs as long as the condition is True.
Syntax:
while condition:
statementi = 1
while i <= 5:
print(i)
i += 1Important:
- Always update the variable inside the loop
- Otherwise, it becomes an infinite loop
i = 1
while i <= 5:
print(i)This will run forever because i never changes.
Stops the loop completely.
for i in range(1, 10):
if i == 5:
break
print(i)Output:
1
2
3
4
Skips the current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)Output:
1
2
4
5
Use for loop when:
- Number of repetitions is known
Use while loop when:
- Repetition depends on a condition
- Forgetting to update variable in
whileloop - Wrong indentation
- Using incorrect range values
- Creating accidental infinite loops
- Print numbers from 1 to 20
- Print even numbers from 1 to 20
- Print multiplication table of a number
- Count from 10 down to 1
- Print each character of a word
Example:
num = int(input("Enter number: "))
for i in range(1, 11):
print(num * i)