0% found this document useful (0 votes)
22 views

While Loops - NOTES

Uploaded by

baabaasheep50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

While Loops - NOTES

Uploaded by

baabaasheep50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

LOOPS

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.

Real World Examples


While you not facing a wall, walk forward (most commonly used in Robotics).

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

1. To print a number as long as it is less than 4


In this example we will consider a number and print it until and unless it is less than 4.

In [ ]:
num = 1

while num < 4:


print(num)
num = num+1

Important Pointers

The variable "num" is given the value of 1 initially.

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.

2. To print a number from 0 till 7 including both 0 and 7.


In this program we are printing the number from 0 till 7. Here we also want to print the value of 7 to be printed.
Hence in the condition, we check whether num is less than or equal to 7 instead of only less than.

In [ ]:

num_1 = 0

while num_1 <= 7:


print(num_1)
num_1 = num_1+1

same thing achieved using for loops.


In [ ]:
for i in range(8):
print(i)

3. Using "continue"
Few pointers related to continue

continue is used to omit or skip a certain part of the code.


As soon as the program encounters the continue statement, it stops the current iteration and the control is
transferred back to the beginning of the loop.
This is especially helpful when you don't want to include one particular number or string and remaining all
should be included. In such cases, usually continue is used.

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)

4. Print a series of even numbers using while loops and continue


Now, let us increase the complexity. Earlier we excluded only one element. Now suppose, I want to print only
even numbers, say from 2 to 20. This means that we have to exclude all the odd numbers appearing in between.

How to do ? Let us see in the below program.


How to do ? Let us see in the below program.

In [ ]:
i = 0
while i < 19:
i = i + 1
rem = i % 2
if rem != 0:
continue
print(i)

1. Print numbers in a reverse order using while loop


Till now we saw the programs in which we printed the numbers in an increasing order only. What if I want to
design a Reverse Counter. Like how it is used in a Space Ship. 10, 9, 8 etc.

Let us see how to do that.

In this example I am desiging a Reverse Order Counter from 5 till 1

In [ ]:
count = 5
while count > 0:
print(count)
count = count - 1

print("Reverse Order Printing !")

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 = []

while age < 120 or age != 0:


age = int(input("Enter the age: "))

if age > 120 or age == 0 or age == 999:


break
age_list.append(age)

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: ")

while name == "CHIREC":

user_name = input("Accept User name: \n Type EXIT to exit the System. ")
if user_name == "EXIT":
print("Exiting the System.")
break

3. Build a program to accept the scores and keep on adding them !!


This is a Simple addition of numbers till the exit condition is entered. In real life it can be used to build a simple
Billing system.

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

What was the problem in the above code ?

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.

Another Example of an Infinite 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. !

4. Fixing the above code !!


In [ ]:
i = 0
score = 0
total = 0
print("Enter 999 to exit ")
while i != 999:
score = int(input("Enter the score: "))
if score == 999:
print("Bye !! Take Care !!")
break

total = total + score


print("The score entered is: ", score, " and the total is ", total)
i= i + 1

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.

1. Count the digits in a number.


This program is to count the number of digits in a Positive Number

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)

3. Scoring system for a Badminton Game.


This program is a simulation of Scoring system in a game of Badminton. The total points scored by any one
player should reach 11. Then the loop will stop its execution.
In [ ]:
player1 = input("Enter the name of player 1: ")
player2 = input("Enter the name of player 2: ")

status = ''
points_won = ''
p1 = p2 = score = total_score = p1_total = p2_total = 0

#print("Type GAME OVER to exit !!")


while total_score != 21:
#while status != "exit":
#print ("exit to exit. ")
#status = input("Enter status !")
player = input("Who scored ?")

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

elif player == player2:


p2 = int(input("Enter for p2:"))
#while p1_total != 11:
p2_total = p2_total + p2
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 [ ]:

Design a Voting System.


There are 3 Candidates.
For the First candidate, user has to select 1, for the second 2 and for the third 3.
If user enters any other value than this, then throw an error and exit the loop.
Then take counters for each candidate and initialize them to 0.
Ask how many people are there to vote.
Then using for and range, start the voting process. For each candidate who is selected, increase the counter
for that candidate by 1.

Displaying the Candidate List.

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"

print("To Vote for Iron Man choose 1. ")


print("To Vote for Spiderman choose 2. ")
print("To Vote for Batman choose 3. ")
print("\n ")

print("Enter only positive integers between 1 and 3. ")


print("Enter 999 to stop Voting. ")

#num_voters = int(input("How many voters today ?"))

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

elif choice == 999 and num_voters == 0:


vote = "N"
break

elif choice == 999:


print("The Voting ended. ")
num_voters = num_voters
print("The total number of Voters today is: ", num_voters)
break

else:
print("Wrong Selection. ")
voting = "Fail"
break

if voting != "Fail" and vote != "N":


if count_iron > count_spidey and count_iron > count_bat:
print("Iron Man got ", count_iron, "Votes and is the winner")

elif count_spidey > count_bat and count_spidey > count_iron:


print("Spiderman got ", count_spidey, "Votes and is the winner")

else:
print("Batman got ", count_bat, "Votes and is the winner")
else:
print("The Voting process was aborted/no votes recorded !!!")

You might also like