Login

Back

Average - Answers

Q1. Type the code in and get it working.
Q2.
The program starts by making a comment about what it does. It then initialises a variable, prints a heading and asks the user how many numbers they want to average. A counter is initialised. The program prints what number to enter, the user enters the number and when all of the numbers have been entered, the average is calculated.
Q3. Initiailisation occurs on lines 3 and 7. It means giving a variable a starting value. For numbers this usually but not always means zero. For strings, it is often the empty string.
Q4. Variables are initialised so the programmer is confident what is in them when the program starts.
Q5. The program has been made easier to read by using indentation, comments, spacing and meaningful variable names.
Q6. end=" " puts a space at the end of the print line instead of a <RETURN>. It stops the cursor going to the next line.
Q7. Use current_number += 1
Q8.

#Calculate the average

sum = 0.0
count = 0
enter_number = "y"

print ("Calculate the average of some numbers.")

while enter_number == "y":
     print ("\nNumber",count+1, end=" ")
     number = float(input("\tEnter a number: "))
     sum = sum + number
     count = count + 1
     enter_number = input("Would you like to enter another number? Please enter y for yes and any other key for no >>> ")

print("\n\nThe average was:",sum/count)

input("Press <ENTER> to quit >>> ")

Q9. Use the round function.

print("\n\nThe average was:",round(sum/count,2))

Q10. Students might improve the layout of the messages at a basic level. At a higher level, they could try to write a program where you just keep entering numbers and pressing <ENTER> after each one rather than asking if you want to enter another number. The program is stopped by entering in a 'sentinel' e.g. -999. 

#Calculate the average

sum = 0.0
count = 0

print ("Calculate the average of some numbers.")

enter_number = float(input("Enter a number: "))
while enter_number != -999:
     sum = sum + enter_number
     count = count + 1
     enter_number = float(input("Next number >>> "))

print("\n\nThe average was:",round(sum/count,2))

input("Press <ENTER> to quit >>> ")

Back