logo codesdope

While Loop in Python


Example of multiplication table of 14

i = 1
while i<=10:
	print i*14
	i=i+1
Output
14
28
42
56
70
84
98
112
126
140

You just got the table of 14! Let's see how:
While is a loop. Loop is something which repeats the codes inside its body till its condition gets getting satisfied.

i=i+1 - Let me first explain this. Let 'i' be 2. Then, 'i+1' is 3. Thus i = i+1 is equivalent to i = 3. So finally, our i is 3. I know that it is a bit different from what you do in maths but you are gonna learn it soon. Let's see an example to get it more clearly

i = 5
i = i+5
print i
i = i+10
print i
i = i+ 2
print i
i = i-10
print i
Output
10
20
22
12

The priority of '=' operator is lesser than that of '+' and '-'. So, it is also lesser than *, / and **.

Initially, the value of i is 5. Now, i = i+5 - This will add 5 to the initial value of i (i.e. 5) because priority of + is greater that that of =. So, i+5 will be calculted first and then the sum will be assigned to 'i'. So, the value of i now becomes 10. So, this expression is equivalent to i = 10.
Now, i = i+10 - Similarly, this statement will add 10 to i ( 'i' is 10 ), so, the expression will be i = 20.
And at last, subtracting 10 from i will make the value of i equal to 12.

Let's go through the previous 'while' code.

Condition in while is i<=10. Initially, i is 1. So, the condition is satisfied ( i is less than 10 ). So, the codes inside the body of while will be executed and 14*i will be 14*1 i.e. 14 will be printed on screen and then i = i+1 will increase the value of i by 1. So, now i is 2.
Again the condition of the loop is satisfied ( 2 is less than 10 ). So, now 14*i will be 14*2 i.e. 28 will be printed on screen and i = i+1 will increase its value by 1 and i will become 3 now.
Again, the condition of the loop will be satisfied and 42 will be printed on the screen.
When i will become 10 then 140 will be printed and i = i+1 will make i 11 and now the condition in while loop ( i <= 10 ) will not be satisfied and the loop will stop and rest of the codes after the while loop will be executed.

So now you know that in the above example, the while loop will stop when i becomes greater than 10.

Notice that the body of while is also represented by equal indentation ( margin ) from left.
while loop in python

The following animation will also help you to understand the while loop.

gif of while loop in Python

One more example (including if/else):

 #initially more is 'True' to run the while loop for atleast once
more = True
while more==True:
	'''Taking marks from user for marks'''
	name = raw_input("Enter your name >>>")
	maths_marks = input("Maths marks >>>")
	science_marks = input("Science marks >>>")
	english_marks = input("English marks >>>")
	comupter_marks = input("Computer marks >>>")
	total = maths_marks+science_marks+english_marks+comupter_marks
	 # using 400.0 to get faction value else if total will be less than 400(and mostly it will be) then it will be 0
	percentage = (total/400.0)*100
	print name,", your total marks is",total,"and your percentage is",percentage

	#User have to enter y if he want to run it again
	a = raw_input("Want to enter more y/n >>>")
	if a!="y":
		#if user enters other than 'y' then making 'more' to 'False' to stop the loop. As condition in while will not be satisfied then
		more = False
Output
Enter your name >>>sam
Maths marks >>>90
Science marks >>>92
English marks >>>85
Computer marks >>>94
sam , your total marks is 361 and your percentage is 90.25
Want to enter more y/n >>>y
Enter your name >>>rai
Maths marks >>>98
Science marks >>>82
English marks >>>89
Computer marks >>>90
rai , your total marks is 359 and your percentage is 89.75
Want to enter more y/n >>>n

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' if the user wants to calculate more or not.
Now, if the user enters 'n', then value of more will become False and then 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 effect on the variable more, and the loop will be executed again.

The above 'while' will run till 'more' is true and it can change if we don't give 'y' to 'a'. (if a!= "y" -> more = False). And if we enter 'y', then the whole loop will run again because 'more' is not changed and is still True.

Break while at our wish


'break' is used to come out of while loop whenever we want. Let's write the above example in a bit different way.

#running while loop forever. As condition is always 'True'
while True:
	name = raw_input("Enter your name >>>")
	maths_marks = input("Maths marks >>>")
	science_marks = input("Science marks >>>")
	english_marks = input("English marks >>>")
	comupter_marks = input("Computer marks >>>")
	total = maths_marks+science_marks+english_marks+comupter_marks
	percentage = (total/400.0)*100
	print name,", your total marks is",total,"and your percentage is",percentage

	a = raw_input("Want to enter more y/n >>>")
	if a == "n":
		#using 'break' to come out from loop
		break
Output
Enter your name >>>sam
Maths marks >>>90
Science marks >>>92
English marks >>>85
Computer marks >>>94
sam , your total marks is 361 and your percentage is 90.25
Want to enter more y/n >>>n

While True - Loop will run forever unless we stop it because the condition of while is always True.
We can stop it using break statement. If loop will encounter break, then the compiler will stop the loop without checking anything else further.
if a == "n" (a is equal to "n") the loop will break as we have used 'break' there.
This means that if the user enters n, then the body of if will get executed and break will stop the loop.

If you have completed up till here, then go and take a chocolate break because it is a big achievement in itself or wait and take it after this section finishes.

Infinite loop example

while True:
	print 1
Output
1
1
1
1
1
1
1
1
1
1
...

This example was only to show you infinte loop. As the condition is always true, the loop will run forever( infinite loop ).

Press ctrl+c to stop this loop

Nesting of loop


Nesting means having one loop inside another loop. It means to have a loop inside the body of other loop. You have already studied about having one 'if' 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
Output
*
**
***
****
*****

Here, 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 will be executed and "*"*1 ( b is 1 ) i.e "*" will be printed and b will become 2 and a will become 4.
Now, inner while loop will be executed again ( as b is 2 and b<=5 ), so "*"*2 i.e. "**" will be printed and both b and a will become 3.
Again, only the inner loop will be executed and "*"*3 i.e. "***" will be printed. In the last iteration of the inner while loop i.e. with b equals 5, "*"*5 i.e. "*****" will be printed and b will become 6 and a will become 0.
Again the condition of the inner while loop will be checked but it will be found false ( as b is 6 ).
Now, the second iteration of outer while will occur but since a is 0, so its condition is also false. So, it will also stop.

In short, there is nothing new in nesting of loops. Inner loop is like all the other statements of a loop, which after executing once, it will be completed first and then rest of the statements of the outer loop will be 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
Output
*
**
***
****
*****
*
**
***
****
*****
*
**
***
****
*****
*
**
***
****
*****
*
**
***
****
*****

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 but 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 = input()
print "Give upper limit of dice"
b = 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 raw_input() == 'q': #if 'q' is entered then come out of loop 
		break;
Output
Give lower limit of dice
1
Give upper limit of dice
6
type q to Quit or any other key/enter to continue
>>> 5
>>> 4
>>> 2
>>> 1
>>> 6
>>> 3
>>> 2
>>> 3
q

We are importing 'randint' function from '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. And rest of the parts must be clear. We are setting the limits of random numbers generated by taking the lower limit as 'a' and the upper limit as 'b'.

In theory, there is no big difference between theory and practice. But in practice, there is.
-Yogi Berra

Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.