Playing with loops makes programming fun. Before we try to understand loop, you should be thorough with all the previous topics of Python. If not, practice a considerable amount of problems on all the previous topics.
Suppose, we have to print the first 10 natural numbers.
One way to do this is to print the first 10 natural numbers individually using
print(). But what if you are asked to print the first 100 natural numbers? You can easily do this with the help of loops.
Loops are used to repeat a block of code again and again.
Basically, there are two loops in Python:
- while loop
- for loop
In this chapter, we will read about the while loop. We will go through the for loop in the next chapter.
Python while Loop
Let's first look at the syntax of while loop.
Python while loop Syntax
while condition: statement statement ...
The body of the while loop consists of all the indented statements below
while loop checks whether the condition is True or not. If the condition is True, the statements written in the body of the
while loop are executed. Then again the condition is checked, and if found True again, the statements in the body of the
while loop are executed again. This process continues until the condition becomes False.
while loop repeats the statements inside its body till its condition becomes False.
Python while loop Examples
Let’s print the first 10 natural numbers using a while loop.
n = 1 while n <= 10: print(n) n = n + 1
The condition of the
while loop is
n <= 10.
The body of the
while loop consists of
n = n + 1. These two statements will get executed only if the condition is True.
First we assigned 1 to a variable
while n <= 10: → The condition
n <= 10 is checked. Since the value of
n is 1 which is less than 10, the condition becomes True and the statements in the body are executed.
The value of
n i.e. 1 is printed and
n = n + 1 increases the value of
n by 1. So, now the value of
n becomes 2.
Now, again the condition is checked. This time also
n <= 10 is True because the value of
n is 2. So, again the value of
n i.e., 2 gets printed and the value of
n is increased to 3.
In this way, when the value of
n becomes 10, again the condition
n <= 10 is True for the tenth time and 10 gets printed. Now,
n = n + 1 increases the value to
n to 11.
This time, the condition
n <= 10 becomes False and the loop gets terminated.
Checking the condition and executing the body consists of one iteration. Therefore, ten iterations took place in the above example.
Quite interesting. Isn't it!
The following animation will also help you to understand the implementation of the
Let's print the multiplication table of 14 using a
i = 1 while i<=10: print(i*14) i=i+1
In this example, the condition of the
while loop is
i is 1.
In the first iteration, the condition is satisfied (1 is less than 10). Therefore, the statements in the body of
while are executed -
14*i ( 14*1 = 14 ) gets printed and then
i = i+1 increases the value of
i by 1 making it 2.
In the second iteration, again the condition of the loop is satisfied (2 is less than 10). Therefore, again the statements in the body are executed -
14*i ( 14*2 = 28 ) gets printed and then
i = i+1 increases the value of
i by 1 making it 3.
In the third iteration, again the condition of the loop is satisfied and 42 gets printed on the screen.
In the tenth iteration, when
i becomes 10, 140 gets printed and
i = i+1 makes the value of
i equal to 11.
Since the value of
i is now 11, the condition of the while loop (
i <= 10) becomes False and the loop gets stopped and the rest of the statements after the
while loop gets executed.
So now you know that in the above example, the
while loop will stop when
i becomes greater than 10.
One more example (including if/else):
#initially more is 'True' to run the while loop for at least once more = True while more == True: '''Taking marks from user''' name = input("Enter your name >>>") maths_marks = int(input("Maths marks >>>")) science_marks = int(input("Science marks >>>")) english_marks = int(input("English marks >>>")) comupter_marks = int(input("Computer marks >>>")) total = maths_marks + science_marks + english_marks + comupter_marks percentage = (total/400)*100 print(name, ", your total marks is", total, "and your percentage is", percentage) #User has to enter y if he want to run it again a = input("Want to enter more? y/n >>>") if a!="y": #if user enters anything other than 'y', then 'more' is set to 'False' to stop the loop. more = False
The code inside the body of
while is simple. It is taking marks as input and calculating the percentage and printing it on the screen.
Again it is asking the user to press 'y' or 'n' to know if the user wants to calculate more or not.
Now, if the user enters 'n', then the value of
more will become False and then the condition of the loop (
more == True) will not be satisfied and thus the loop will stop. But if the user enters 'y', then there will be no change in the value of the variable
more, which will satisfy the condition of the loop and the loop will be executed again.
while loop will run till
more is True and it can change if we don't give 'y' to
if a!= "y" → more = False). And if we enter 'y', then the whole loop will run again because the value of
more is not changed and is still True.
Python Infinite Loop
A loop is called an infinite loop if its condition is always True. It is called so because it will keep on executing its body forever. Below is an infinite loop created using a
while True: print(1)
Python Nesting of Loop
Nesting means having one loop inside another loop, i.e., to have a loop inside the body of another loop. You have already studied about having one if statement under another. This is also similar. Let's see an example first.
a = 5 b = 1 while a>0: while b<=5: print("*"*b) b = b+1 a = a-1
a is 5 and
b is 1.
In the first iteration of the outer while loop,
a is 1 and the inner
while loop is inside the body of the outer
while loop. So, the inner
while loop is executed and
"*"*1 (b is 1) i.e, "*" gets printed and
b becomes 2 and
a becomes 4.
Now, the inner
while loop gets executed again (as
b is 2 and
b <= 5). So
"*"*2 i.e. "**" gets printed and both
a become 3.
Again, the inner loop gets executed and
"*"*3 i.e., "***" gets printed. In the last iteration of the inner
while loop with
b equals 5, "*"*5 i.e., "*****" gets printed and
b becomes 6 and
a becomes 0.
Again the condition of the inner
while loop is checked but it is found False (as
b is 6).
Now, the second iteration of the outer while loop occurs but since a is 0, so its condition is also False. Therefore, it will also stop.
In short, there is nothing new in nesting of loops. Inner loop is like all the other statements in the body of a loop, after the execution of which, the rest of the statements in the body of the outer loop are executed.
Let's have a look at one more example on this:
a = 5 while a>0: b = 1 while b<=5: print("*"*b) b = b+1 a = a-1
Try to understand this example yourself. Just go step by step with every while loop and you will understand this.
Let's create your own digital dice.
Though this is not graphical, we will construct the working structure. You can learn to link graphics to this or any game after completing this course. For now, let's do this first.
#Digital dice #importing random function to genterate random number from random import randint print("Give lower limit of dice") a = int(input()) print("Give upper limit of dice") b = int(input()) print("type q to Quit or any other key/enter to continue") while True: print(">>> "+str(randint(a,b))) #randint is generating random number between a and b if input() == 'q': #if 'q' is entered then come out of loop break
We are importing the
randint() function from the
random library of Python. This function generates a random number between two integers given to it. You can find more about it in Python documentation. The rest of the parts must be clear. We are setting the limits of the random numbers generated by taking the lower limit as 'a' and the upper limit as 'b'.
Make sure to read articles in Further Reading at the end of this chapter.