In this tutorial, I will discuss about for loops in python,how to use for loops with examples, the range function which will be helpful while working with the loops.
Loops in Python
In general, statements in a program are executed sequentially: first statement followed by second and so on. But there may be a situation when we need to execute a block of statements multiple number of times.
Python language provides various complex control structures for handling such situations.
An iteration statement or repeat statements are used to execute a block of statements multiple number of times. These are also called as looping statements. Python programming language has the following type of looping statements:
-
Counting Loops: The loops that repeats a block of statements multiple number of times. Python’s for loop is a counting loop.
-
Conditional Loops: The loops that repeat a block of statements until a certain condition evaluates to be True. Python’s while loop is a conditional loop.
Let’s learn about the for loop.
For Loop
A for loop executes the block of statements within the loop multiple number of times. It is also used to iterate through sequence like string, lists, tuples and other iterable type of objects. Iterating over a sequence is also known as traversal.
Syntax of for loop:
for <target> in <sequence>:
# Block of statements to repeat
Here target is a variable which is assigned items in sequence one by one and executes the block of statements in loop body for each value in the sequence.
The for loop runs until it runs for last item in the sequence.
Body of the for loop is a block of statements which generally contains manipulation using target variable and is separated from rest of the code using indentation.
Consider the below example:
list1 = [2,4,6,8]
for val in list1:
print("value = ", val)
print("square of value = ", val * val)
value = 2
square of value = 4
value = 4
square of value = 16
value = 6
square of value = 36
value = 8
square of value = 64
As we can see in the above example, both print statements inside the for loop block are executed for each element of the list.
This is known as iterating or traversing through the list. A for loop can also be used for traversing through a string or a tuple.
Notice that we have not defined val variable also known as loop variable before it is used in the for loop. The loop variable need not be predefined to use it in for loop.
Take a look at examples below :
Example 1 :
line = "I am here to learn python programming language"
count1 = count2 = 0
for ch in line:
if(ch=="a"):
count1+=1 #increments count1 variable each time a is encountered
elif(ch==" "):
count2+=1 #increments count2 variable each time space is encountered
print("number of a in line : ",count1)
print("number of space in line : ",count2)
number of a in line : 5
number of space in line : 7
In the above example, for loop is used to count the number of occurences of character ‘a’ and space by iterating or traversing through the string named line.
Example2 :
tuple1 = ("Learning", "is", "fun")
for tup in tuple1:
print(tup, end=' ')
Learning is fun
The above example shows the use of for loop to print out the elements if a tuple datatype which is similar as it is used for a list.
The range function
Now suppose we want to print all even numbers from 0 up to 50, using the simple technique we will need to create a list of all the even numbers from 0 to 50. For such cases python provides a special function called range()
.
The code : range(10)
will generate numbers 0 to 9 (total 10 numbers). To generate a list of numbers from a particular number up to another number the following syntax of range is used.
Syntax of range()
:
range(start, stop, step_size)
Here start defines the value from which the list starts generating and stop defines the last value up to which it should be generated.
Step size is used to define the size of step (or addition) after each value of the list is generated. This is 1 by default i.e. it increments the value by 1 which can be changed by specifying a value for step size.
Consider the following examples:
print(range(5))
print(list(range(5)))
print(list(range(9,2,-1)))
print(list(range(0,50,2)))
range(0, 5)
[0, 1, 2, 3, 4]
[9, 8, 7, 6, 5, 4, 3]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]
Notice in the above example, we have used list()
function to convert the output of range()
into a list which is then shown in the output.
This is because range()
does not store the values in memory that is the reason the 1st print statement has not print the list from 0 to 5 built instead just shown the range()
in its basic syntax.
This range()
function is used in for loop to iterate through a sequence of numbers or repeat a block of statements given number of times. Below are some examples :
for i in range(5):
print(i, end=' ') #end = ' ' is used to print the values in a single line
0 1 2 3 4
for i in range(5,0,-1):
print(i,' : ', i*i)
5 : 25
4 : 16
3 : 9
2 : 4
1 : 1
list1 = [10,20,30,40]
for i in range(len(list1)): #len(list1) provides the length of list1 to range function.
print(list1[i], end= ' ')
10 20 30 40
While Loop
We have discussed about how for loop is used to repeat a certain block of statements given number of times. But what if we don’t know how many times should the block of statements run ?
In that case while loop is used. A while loop always checks a predefined condition before executing the block of statements.
A while loop is a conditional loop that will repeat the block of statements as long as the test condition evaluates to be True.
The general syntax of while loop is :
while logical condition:
#Block of statements to repeat
When the program first encounters the while loop, it evaluates the logical condition if it is True then the control passes to the body of the loop.
The loop iterates while the logical condition evaluates to True. When the condition becomes False, program control passes to the line after the loop body. The condition is checked after each iteration of the loop.
The body of while loop is determined through indentation in python. It starts with indentation and the first unindented line marks the end of loop body.
Let’s take an example to understand this more clearly:
a = 5
while a > 0:
print("a : ",a)
a = a - 1
a : 5
a : 4
a : 3
a : 2
a : 1
Let’s understand the loop elements of a while loop from the above example.
-
Initialization expression : Before entering into the while loop, the loop control variable needs to be initialized first. And an uninitialized variable cannot be used in a while loop.
-
Test expression : This is the condition which gets evaluated every time the loop iterates. This expression contains the loop control variable. If the test expression evaluates to True then loop body is executed, otherwise the loop is terminated.
-
Body of the Loop : This is the block of statements which we need to repeat whenever the test expression is True.
-
Update expression : This expression is used to change/update the value of loop variable. This expression is present inside the body of the loop.
Let’s look at the example again and define the elements properly.
a = 5 # This is the initialization expression and a is the loop control variable
while a > 0: # Here a > 0 is the test expression of the loop
print("a : ",a) # This statement forms the body of the loop.
a -= 1 # This is the update expression which changes/updates the loop control variable a and also forms the body of the loop.
NOTE : The loop control variable in while loop needs to be initialized or must have a value before used in the loop. And uninitialized variables cannot be used in the while loop.
Let’s have a look at another example of while loop:
n = 1
sum = 0
while n <= 10:
sum = sum + n
n = n + 1
print("Sum =",sum)
Sum = 55
In the above code, we perform addition of numbers from 1 to 10. The test expression (n <= 10 ) will be true until n is less than or equal to 10. Then we change/update the value of n using the update expression. Without this, the code may result into an infinite loop.
Finally the result is displayed.
Conclusion
In this tutorial, we have discussed about loops in python. We have seen for loop and while loop in detail. We have also seen the use of range function for generating a sequence of numbers.
If you have any questions please comment below also share your views and suggestions in the comment box.