Back

Average

Q1. Enter and run this code:

1    #Calculate the average
2
3    sum = 0.0
4
5    print ("Calculate the average of some numbers.")
6    count = int(input("How many numbers will you enter: "))
7    current_number = 1
8
9    while current_number < count+1:
10       print ("\nNumber",current_number, end=" ")
11       number = float(input("\tEnter a number: "))
12       sum = sum + number
13       current_number = current_number + 1
14
15   print("\n\nThe average was:",sum/count)

Q2. Describe how this program works, step by step.
Q3.
On what lines do initialisation occur? What is meant by initialisation?
Q4.
Why should variables be initialised?
Q5.
Describe the ways that this program has been written so it is as easy as possible to understand.
Q6.
Explain the purpose of end=" " on line 10.
Q7.
Rewrite line 13 using +=
Q8.
In the above program, you have to enter how many numbers you want to average. Your task is to write a program that lets any number of numbers be entered, until the user says they have finished. The pseudo-code for one solution is as follows:

Comment what the program is about
Initialise sum = 0.0
Initialise count = 0
Initialise enter_number to "y"

print title
while enter_number = y
     print "number", count+1
     input a number
     sum = sum + number
     count = count + 1
     display message; 'Y' for another number or any other key to quit.
print "The average is sum/count
display 'Press enter to quit'

Turn the above pseudo-code into Python code and run and test it.
Q9.
If you enter these numbers to find the average: 5,  10 and 2, the answer is 5.666666666666667
How can you round this down to two decimal places?
Q10.
Can you make any improvements to this program, perhaps in the way it is laid out or functions?

Back