In computer programming, loops are used to repeat a block of code.
For example, if we want to show a message 100 times, then we can use a loop. It's just a simple example; you can achieve much more with loops.
There are 2 types of loops in Python:
Python for Loop
In Python, the
for loop is used to run a block of code for a certain number of times. It is used to iterate over any sequences such as list, tuple, string, etc.
The syntax of the
for loop is:
for val in sequence: # statement(s)
val accesses each item of sequence on each iteration. Loop continues until we reach the last item in the sequence.
Flowchart of Python for Loop
Example: Loop Over Python List
In the above example, we have created a list called languages.
Initially, the value of
language is set to the first element of the array,i.e.
Swift, so the print statement inside the loop is executed.
language is updated with the next element of the array and the print statement is executed again. This way the loop runs until the last element of an array is accessed.
Python for Loop with Python range()
A range is a series of values between two numeric intervals.
We use Python's built-in function
range() to define a range of values. For example,
values = range(4)
Here, 4 inside
range() defines a range containing values 0, 1, 2, 3.
In Python, we can use
for loop to iterate over a range. For example,
# use of range() to define a range of values values = range(4) # iterate from i = 0 to i = 3 for i in values: print(i)
0 1 2 3
In the above example, we have used the
for loop to iterate over a range from 0 to 3.
The value of
i is set to 0 and it is updated to the next number of the range on each iteration. This process continues until 3 is reached.
||The loop is terminated|
Note: To learn more about the use of
for loop with range, visit Python range().
Python for loop with else
for loop can have an optional
else block as well. The
else part is executed when the loop is finished. For example,
digits = [0, 1, 5] for i in digits: print(i) else: print("No items left.")
0 1 5 No items left.
for loop prints all the items of the digits list. When the loop finishes, it executes the
else block and prints
No items left.
Note: The else block will not execute if the for loop is stopped by a break statement.