Loops in Python
Loops are an essential part of programming. They allow you to repeat a block of code multiple times, without having to write the same code over and over. In Python, there are two main types of loops: for
loops and while
loops. This article will cover both types of loops, along with some common loop control statements.
for
Loops
A for
loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The basic syntax of a for
loop in Python is as follows:
for item in sequence:
# code block to be executed
Here, item
is a variable that will take on the value of each item in the sequence
, and the code block under the loop will be executed for each item. Let’s look at some examples:
Iterating over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
Iterating over a String
for letter in "Python":
print(letter)
P
y
t
h
o
n
Using the range()
Function
The range()
function is commonly used in for
loops to generate a sequence of numbers. It takes up to three arguments: start
, stop
, and step
. If only one argument is provided, it generates a sequence from 0
to stop-1
. If two arguments are provided, it generates a sequence from start
to stop-1
. Let’s see some examples:
for i in range(5):
print(i)
0
1
2
3
4
for i in range(1, 6):
print(i)
1
2
3
4
5
for i in range(0, 10, 2):
print(i)
0
2
4
6
8
In this example, the range(0, 10, 2)
function generates a sequence of numbers from 0
to 9
with a step size of 2
.
range(start, stop, step)
generates a sequence of numbers from 0
to n-1
by default. If you want to start the sequence from a different number, you can provide the starting value as the first argument. If you want to generate a sequence up to a specific number, you can provide the stop value as the second argument. If you want to generate a sequence with a specific step size, you can provide the step value as the third argument.While Loops
A while
loop is used to execute a block of code as long as a condition is true. The basic syntax of a while
loop in Python is as follows:
while condition:
# code block to be executed
Here, the condition
is an expression that is evaluated before each iteration of the loop. The code block under the loop will be executed as long as the condition is True
. Let’s look at an example:
Example: Countdown using a While Loop
count = 5
while count > 0:
print(count)
count -= 1
5
4
3
2
1
In this example, the count
variable is initialized to 5
, and the while
loop continues as long as count
is greater than 0
. The count
variable is decremented by 1
in each iteration, and the loop prints the value of count
until it reaches 0
.
Infinite Loops
while
loops, as they can result in an infinite loop if the condition never becomes False
. For example, the following code will result in an infinite loopwhile True:
print("This is an infinite loop!")
If you accidentally run code that results in an infinite loop, you can stop the program by pressing Ctrl+C
in the terminal.
Loop Control Statements
Python provides several loop control statements that allow you to change the behavior of loops. The common loop control statements are:
1. break
The break
statement is used to exit the loop prematurely. When break
is encountered in a loop, the loop is terminated immediately, and the program continues with the next statement after the loop. Let’s look at an example:
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
2. continue
The continue
statement is used to skip the rest of the code block inside the loop for the current iteration and continue with the next iteration of the loop. Let’s look at an example:
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
3. pass
The pass
statement is used as a placeholder when a statement is required syntactically but you do not want to execute any code. It is often used as a placeholder for future code. Let’s look at an example:
for i in range(5):
if i == 2:
pass
print(i)
0
1
2
3
4
In this example, the pass
statement does nothing, and the loop continues executing the next statement.
Nested Loops
Python allows you to nest loops within each other. This means you can have a loop inside another loop. Let’s look at an example of a nested loop:
for i in range(3):
for j in range(2):
print(f"({i}, {j})")
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
In this example, the outer loop iterates over the values 0
, 1
, and 2
, while the inner loop iterates over the values 0
and 1
. The print
statement inside the inner loop prints the values of i
and j
.
Conclusion
Loops are a powerful feature in Python that allow you to repeat a block of code multiple times. By using for
loops and while
loops, along with loop control statements like break
, continue
, and pass
, you can create complex programs that perform repetitive tasks efficiently. Practice writing loops and experiment with different loop control statements to become more comfortable with using loops in Python.
In the next article, we will learn about functions and modular programming in Python.