A loop is used to execute a block of code repeatedly based on a condition or a sequence of values.
For example, if we want to print "Hello Python" five times, we don't need to write five print statements. We can use a loop.
Example Without Loop
print("Hello Python")
print("Hello Python")
print("Hello Python")
print("Hello Python")
print("Hello Python")
Example With Loop
for i in range(5):
print("Hello Python")
Output:
Hello Python
Hello Python
Hello Python
Hello Python
Hello Python
Here, the loop executes the print statement five times.
Types of Loops in Python
Python mainly provides two types of loops:
for loop
while loop
Let's understand both with examples.
- For Loop in Python
A for loop is used to iterate over a sequence such as a list, tuple, string, or range.
Syntax
for variable in sequence:
statements
Example 1: Print Numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Explanation
for starts the loop.
i stores the current number.
range(1, 6) generates numbers from 1 to 5.
print(i) displays each number.
Important: The ending value in range() is excluded.
Example 2: Print Even Numbers
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
Here, 2 is the starting value, 11 is the ending limit, and the last 2 represents the step value.
Example 3: Loop Through a List
fruits = ["Apple", "Mango", "Orange"]
for fruit in fruits:
print(fruit)
Output:
Apple
Mango
Orange
Here, the loop accesses each element from the list one by one.
Example 4: Loop Through a String
name = "PYTHON"
for i in name:
print(i)
Output:
P
Y
T
H
O
N
Here, the loop accesses each character in the string.
- While Loop in Python
A while loop executes a block of code as long as the given condition is True.
Syntax
while condition:
statements
Example 1: Print Numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i = i + 1
Output:
1
2
3
4
5
Explanation
First, i = 1 initializes the variable.
i <= 5 checks the condition.
If the condition is True, the number is printed.
i = i + 1 increases the value by one.
When i becomes 6, the condition becomes False and the loop stops.
Important: Always update the variable in a while loop when necessary. Otherwise, you may create an infinite loop.
Example 2: Print Even Numbers Using While Loop
i = 2
while i <= 10:
print(i)
i = i + 2
Output:
2
4
6
8
10
Top comments (0)