Loops in Python are used to execute a block of code repeatedly until a condition is satisfied.
Python has two main types of loops:
- for loop
while loop
for loop:
A for loop is used to iterate over a sequence like a list, string, or range.
Example:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Explanation:
- i is the loop variable.
- range(1, 6) generates numbers from 1 to 5.
- print(i) prints each number.
- while loop: A while loop executes the code repeatedly as long as the condition is True.
Example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Explanation:
- i = 1 initializes the variable.
- i <= 5 checks the condition.
- i += 1 increases the value by 1.
- When i becomes 6, the loop stops.
- Loop control statements:
Python has three important loop control statements.
Statement: Meaning:
break Stops the loop completely
continue Skips the current iteration
pass Does nothing; acts as a placeholder
break example:
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2
Top comments (0)