Worksheet 5 While loops
Introduction to Python
Worksheet 5: While loops
Below is an example code for a simple program to add up numbers entered by a user and
display the total.
Copy the code below and run it. Then try the challenge below.
#Adder
print("Keeping a running total")
print("***********************\n")
print("Enter numbers to add together then press 0 to exit.")
#Initialise the variables
count = 0
runningTotal = 0
number = int(input("Input the first number: "))
#Add each number together until 0 is entered
while number != 0:
count = count + 1 # (or count+=1)
runningTotal = runningTotal + number
number = int(input("Input next number (0 to finish): "))
#Display the total sum and the number of entries made
print ("You entered ",count," numbers")
print ("Total = ", runningTotal)
input("Press ENTER to exit")
Challenge :
Plan and write a program called GuessMyNumber.py where the computer generates a
random number between 1 and 100 and the user must guess what it is. The program should
indicate whether they are too high or too low and display the final number of attempts at the
end.
#Guess my Number Game
#A classic program that uses a while loop
#Impor5t the random number module
import random
#Display the title and rules
print("Guess the Number Game!")
1
Worksheet 5 While loops
Introduction to Python
ptint("***********************\n")
print("I am thinking of a number between 1 and 100.")
print("Try to guess what it is in a few attempts as possible.\n")
#Initialise the variables and generate a random number between 1 and 100
number = random.randint(1, 100)
guess = int(input("What is your first guess? "))
attempts = 1
#Create the loop
#!= means not equal to
while guess != number:
if guess > number:
print("Too high.")
else:
print("Too low")
guess = int(input("Guess again...: "))
attempts = attempts + 1
print("Well done! you took",attempts, "attempts to guess it was number",number,)
input("\n\nPress ENTER to exit")