FOR LOOP
A loop is used for iterating over a set of statements repeatedly. In Python we have three types of loops for, while and do-while. In this guide, we will learn for loop and the other two loops are covered in the separate tutorials.
Syntax of For loop in Python
for <variable> in <sequence>:
// body_of_loop that has set of statements
// which requires repeated execution
Here <variable> is a variable that is used for iterating over a <sequence>. On every iteration it takes the next value from <sequence> until the end of sequence is reached.
Let’s take a few examples of for loop to understand the usage.
Python – For loop example
The following example shows the use of for loop to iterate over a list of numbers. In the body of for loop we are calculating the square of each number present in list and displaying the same.
// Program to print squares of all numbers present in a list
## List of integer numbers
numbers = [1, 2, 4, 6, 11, 20]
// variable to store the square of each num temporary
sq = 0
// iterating over the given list
for val in numbers:
// calculating square of each number
sq = val * val
//displaying the squares
print(sq)
Output:
1
4
16
36
121
400
Function range()
In the above example, we have iterated over a list using for loop. However we can also use a range() function in for loop to iterate over numbers defined by range().
range(n): generates a set of whole numbers starting from 0 to (n-1).
For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify the step_size, the numbers generated are having a difference of 1. However by specifying step_size we can generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
Let’s use the range() function in for loop:
Python for loop example using range() function
Here we are using the range() function to calculate and display the sum of first 5 natural numbers.
## Program to print the sum of first 5 natural numbers
// variable to store the sum
sum = 0
// iterating over natural numbers using range()
for val in range(1, 6):
# calculating sum
sum = sum + val
// displaying sum of first 5 natural numbers
print(sum)
Output:
15
For loop with else block
Unlike Java, In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block executes only when the loop has completed all the iterations. Lets take an example:
for val in range(5):
print(val)
else:
print(“The loop has completed execution”)
Output:
0
1
2
3
4
The loop has completed execution
Note: The else block only executes when the loop is finished.
Nested For loop in Python
When a for loop is present inside another for loop then it is called a nested for loop. Lets take an example of nested for loop.
for num1 in range(3):
for num2 in range(10, 14):
print(num1, “,”, num2)
Output:
0 , 10
0 , 11
0 , 12
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13
WHILE LOOP
While loop is used to iterate over a block of code repeatedly until a given condition returns false. In the
last tutorial, we have seen for loop in Python, which is also used for the same purpose. The main
difference is that we use while loop when we are not certain of the number of times the loop requires
execution, on the other hand when we exactly know how many times we need to run the loop, we use
for loop.
Syntax of while loop
while condition:
while_body
The body_of_while is set of Python statements which requires repeated execution. These set of
statements execute repeatedly until the given condition returns false.
Flow of while loop
- First the given condition is checked, if the condition returns false, the loop is terminated and the
control jumps to the next statement in the program after the loop. - If the condition returns true, the set of statements inside loop are executed and then the control
jumps to the beginning of the loop for next iteration.
These two steps happen repeatedly as long as the condition specified in while loop remains true.
Python – While loop example
Here is an example of while loop. In this example, we have a variable num and we are displaying the
value of num in a loop, the loop has a increment operation where we are increasing the value of num.
This is very important step, the while loop must have a increment or decrement operation, else the loop
will run indefinitely, we will cover this later in infinite while loop.
num = 1
#it will repeat self while the num1 is less than 10.
while num < 10:
print(num)
#increasing the value of num
num = num + 3
Output:
1
4
7
Infinite while loop
Example 1:
This will print the word ‘hello’ indefinitely because the condition will always be true.
while True:
print(“hello”)
Example 2:
num = 1
while num<5:
print(num)
This will print ‘1’ indefinitely because inside loop we are not updating the value of num, so the value of
num will always remain 1 and the condition num < 5 will always return true.
Nested while loop in Python
When a while loop is present inside another while loop then it is called nested while loop. Lets take an
example to understand this concept.
i = 1
j = 5
while i < 4:
while j < 8:
print(i, “,”, j)
j = j + 1
i = i + 1
Output:
1 , 5
2 , 6
3 , 7
Python – while loop with else block
We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only after
the loop finished execution.
num = 10
while num > 6:
print(num)
num = num-1
else:
print(“loop is finished”)
Output:
10
9
8
7
loop is finished