This article will teach you how to use the Python for loop to execute a code block a set number of times.
In programming, it’s common to wish to run a block of code several times. A for loop is used to accomplish this.
The syntax of a for loop is illustrated below:
for index in range(n): statement
The index is referred to as a loop counter in this form. And n is the number of times the statement will be executed by the loop.
You don’t have to call the loop counter index; you can call it whatever you want.
Python has a built-in function called range(). It’s similar to the print() method in that it’s always present in the programme.
range(n) returns a list of n numbers beginning at zero. It gradually increases the value until it reaches n.
As a result, range(n) generates the following numbers: 0,1, 2,…n-1. It’s worth noting that it’s always less than the total (n).
The following example explains how to display 5 integers from 0 to 4 on the screen using the for loop and the range() function:
for index in range(5): print(index)
Output
0 1 2 3 4
The print(index) statement is executed five times in this example by the for loop.
You can perform something like this to display 5 numbers from 1 to 5 on the screen:
for index in range(5): print(index + 1)
Output
1 2 3 4 5
In this example, we publish the index after increasing it by one in each iteration. There is, however, a better method to go about it.
Specifying the sequence’s initial value in Python
The range() function starts the sequence with a value of zero by default.
You can also use the range() method to specify a starting number, such as this:
range(start, stop)
The range() function increases the start value by one until it reaches the stop value in this syntax.
The following example utilises a for loop to display five integers on the screen, ranging from 1 to 5.
for index in range(1, 6): print(index)
Output
1 2 3 4 5
Specifying the sequence’s increment in Python
In each loop iteration, the range(start, stop) increments the start value by one by default.
To change the start value by a different number, use the range() method in the following format:
range(start, stop, step)
You can give the value that the range() function should increase in this fashion.
The sample below shows all of the odd numbers from 0 to 10:
for index in range(0, 11, 2): print(index)
Output
0 2 4 6 8 10
How to Calculate sum of Sequence in Python?
The for loop statement is used in the following example to calculate the sum of values from 1 to 100:
sum = 0 for num in range(101): sum += num print(sum)
Output
5050
How does it work?
The sum is first set to zero.
Second, in each repetition, the sum is multiplied by an integer between 1 and 100.
Finally, project the total onto the screen.
If you’re a mathematician, you can use the following formula:
n = 100 sum = n * (n+1)/2 print(sum)
Leave a Reply