In Python, loops are used to execute a block of code repeatedly. There are two main types of loops: for
loops and while
loops. Each type of loop serves a different purpose and is used in different scenarios.
For Loops:
A for
loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence.
Use a for
loop when you want to iterate over a sequence, and you know the number of iterations beforehand or you need to go through each element in a collection.
Syntax:
for <variable_name> in <sequence>:
(body of for loop)
The loop continues until the last item in the sequence is reached. Like the while loop, the body of the for loop is also determined through indentation.
Example:
range() Function
To loop through a set of code a specified number of times, we can use the range() function.
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Example:
Note: range(10) is not the values from 0 to 9, but the values from 0 to 9.
The range() function defaults to 0 as a starting value, however, it is possible to specify the starting value by adding a parameter: range(3, 7), which means values from 3 to 7 (but not including 7):
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(1, 10, 2):
for x in range(1, 10, 2):
print(x)
which gives the output:
1
3
5
7
9
Example program 1:
Solution:
Example program 2:
Solution:
Example program 3:
Solution:
Example program 4:
Solution:
Example program 5:
Solution:
Congrats🎉, On Learning the Python For loop concepts.
Happy Learning :)