To handle all of the looping requirements in your script, Python supports two loops:
- for loop
- while loop
Now, we are going to learn about for loop and while loop.
To handle all of the looping requirements in your script, Python supports two loops:
Now, we are going to learn about for loop and while loop.
for loop iterates over each item of the sequence or any other iterable object and it will execute the statements in the for block each time. Refer to the following syntax:
for i in sequence:
for loop body
Here, i is the variable that takes the value of the item inside the sequence on each iteration. This loop continues until we reach the last item in the sequence. This is illustrated in the following diagram:
Refer to the following example:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for i in numbers:
sum = sum + i
print("The sum is", sum)
Output:
The sum is 6
The sum is 11
The sum is 14
The sum is 22
The sum is 26
The sum is 28
The sum is 33
The sum is 37
The sum is 48
The Python range() function will generate a sequence of numbers. For example, range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop, and step size as parameters and range() will be as follows:
range(start, stop, step size).
Step size defaults to 1 if not provided.
For loop example using range() function:
Let's take a look at an example:
for i in range(5):
print("The number is", i)
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
while is a looping statement that will iterate over a block of code until the entered test expression is true. We use this loop when we don't know how many times the iterations will go on. Refer to the following syntax:
while test_expression:
while body statements
In the while loop, first we will check the test expression. The while block will get executed only if the test expression is true. After one iteration, the expression will be checked again and this process continues until test_expression evaluates to false. This is illustrated in the following diagram:
The following is an example of the while loop:
a = 10
sum = 0
i = 1
while i <= a:
sum = sum + i
i = i + 1
print("The sum is", sum)
Output:
The sum is 1
The sum is 3
The sum is 6
The sum is 10
The sum is 15
The sum is 21
The sum is 28
The sum is 36
The sum is 45
The sum is 55