While Loops - NOTES
While Loops - NOTES
In Stage 7 we learnt one type of loops i.e., for loops. This academic year, we will start with another type of loops
which is "while"
while loops
These loops are called as Indefinite loops.
It essentially means that when we don't have the knowledge of how many times the loops is going to be
executed, we make use of "while" loops.
With the while loop, we can execute the statements as long as they are true.
They keep on iterating until the Condition is satisfied OR
Until something is TRUE or FALSE, keep on repeating.
While there are items in Cart, continue the Billing process (Used in E-commerce applications, supermarkets
and any store where billing happens digitally).
Listening to Songs on a Music Player - until we press STOP or the there are no more songs to play in the
Playlist. Used in Spotify, Gaana etc.
Promote a player to the next level in Computer games until the Player quits playing or there are no more
levels left.
Examples
In [ ]:
num = 1
Important Pointers
Observe the Syntax. It is the same as in "if" or "for". i.e, after the statement we should have a colon symbol.
The Condition we are checking is whether the variable "num" is less than 4. If Yes, then it will print the value
of the variable.
Another important piece of code is the line "num = num + 1". It keeps on incrementing the value of the
variable "num". This is to ensure that the program does not end up an infnite loop.
variable "num". This is to ensure that the program does not end up an infnite loop.
Initialy the value would be 1, then it will be increnmented to 2 and again there is a check for the condition
which is satisfied as 2 iss less than 4. It is also printed and the same happens when the value is 3.
Finally when the value is changed to 4 the condition fails and the execution stops.
In [ ]:
num_1 = 0
3. Using "continue"
Few pointers related to continue
Example
For instance, in the below example, I do not want to print 3. So, I use a continue statement. Below is the code for
the same.
In [ ]:
i = 0
while i < 6:
i = i + 1
if i == 3:
continue
print(i)
In [ ]:
i = 0
while i < 19:
i = i + 1
rem = i % 2
if rem != 0:
continue
print(i)
In [ ]:
count = 5
while count > 0:
print(count)
count = count - 1
In [ ]:
2. Accept age from the user. The program should keep on asking age
from the user and then store it in a list. Tell the user to press 999 in the
input to exit the loop.
This is little complex problem as we are using the concept of input as well. In this program we take input from
the user. The input what we are taking is the age. Whatever the value is entered that is stored in a List.
So, how to make the user STOP entering the values. For that we have to include a stopping condition. In this
case, as mentioned in the problem statement, it will be 999.
Hence, as soon as the user enters 999, the program will stop its execution.
In [ ]:
age = 0
age_list = []
for i in age_list:
print(i)
Will the above program work for Negative numbers ? If Yes, then it is wrong ! How will you
fix it ? (Hint: use continue)
3. Suppose you have designed an application which requires the user to enter the school
name as "CHIREC" and then only the user can proceed to enter their Name. Write the code
for it using while loops.
It is pretty simple. In this case, we have to accept the school name. Compare it with "CHIREC". If it is CHIREC
then ask the user to enter his/her name.
In [ ]:
name = input("Enter the School name: ")
user_name = input("Accept User name: \n Type EXIT to exit the System. ")
if user_name == "EXIT":
print("Exiting the System.")
break
In [ ]:
i = 0
score = 0
total = 0
In [ ]:
print("Enter 999 to exit ")
while i != 999:
score = int(input("Enter the score: "))
total = total + score
print("The score entered is: ", score , " and the total is ", total)
i= i + 1
Infinite Loops
This is one of the interesting aspect about while loops. If you do no check the stopping criteria in your program,
the program will never stop executing and will result in an endless infnite loop.
In [ ]:
i = 1
while i ==1:
print(i)
First let us the fix the Score problem and then you will help me fix the above problem. !
As it can be seen in the above code, now we are checking every time whether score is equal to 999 as soon as
the value is entered. If it is 999 then we "break" else the value is accepted and again the score is incremented.
In [ ]:
counter = 0
num = int(input("Enter a positive number. "))
i = num
while num > 0:
num = num //10
counter = counter + 1
if counter >0:
print("The total number of digits in", i, "are", counter)
else:
print("Looks like number of digits were incorrect. ")
2. Reverse a number
This program is to reverse a number.
In [ ]:
num = 123
a = 0
rev = 0
while num > 0:
a = num%10
rev = rev * 10 + a
num = num//10
print(rev)
status = ''
points_won = ''
p1 = p2 = score = total_score = p1_total = p2_total = 0
if player == player1:
p1 = int(input("Enter for p1:"))
#while p1_total != 11:
#p1 = p1 + 1
p1_total = p1_total + p1
total_score = total_score + 1
print("Player 1 Score: " ,p1_total, "Player 2 Score: ",p2_total,"total score: ",
total_score)
if p1_total == 11:
break
if p1_total == 11:
print("player 1 wins!!!")
elif p2_total == 11:
print("player 2 wins!!!")
In [ ]:
In [ ]:
candidate_list = ["Iron Man", "Spiderman", "Batman"]
print("Below are the candidates. ")
for i in candidate_list:
print(i)
Voting Process.
In [ ]:
count_iron = count_spidey = count_bat = 0
voting = " "
vote = "Y"
num_voters = 0
while num_voters < 100:
#for voters in range(100):
choice = int(input("Select your choice: "))
if choice == 1:
num_voters = num_voters + 1
count_iron = count_iron + 1
elif choice == 2:
num_voters = num_voters + 1
count_spidey = count_spidey + 1
elif choice == 3:
num_voters = num_voters + 1
count_bat = count_bat + 1
else:
print("Wrong Selection. ")
voting = "Fail"
break
else:
print("Batman got ", count_bat, "Votes and is the winner")
else:
print("The Voting process was aborted/no votes recorded !!!")