question archive Write a program that computes the average of a collection of values entered by the user
Subject:Computer SciencePrice:3.86 Bought8
Write a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. Your program should display an appropriate error message if the first value entered by the user is 0.
Hint: Because the 0 marks the end of the input it should not be included in the average.
#!/usr/bin/env python3 # get initial input n = float(input()) # raise ValueError if user initial input is zero if n == 0: raise ValueError("First value cannot be zero") # initialize a list called numbers with the initial input as the first element numbers = [n] # loop while sentinel value is not entered while n != 0: # get user input n = float(input()) # add input to numbers list numbers.append(n) # calculate average by summing all the numbers and dividing by the # number of elements in the list minus 1 # minus 1 because it includes the last zero average = sum(numbers) / (len(numbers) - 1) # print the average print(average)
Step-by-step explanation
The code is already heavily commented and should be self explanatory.
#!/usr/bin/env python3 # get initial input n = float(input()) # raise ValueError if user initial input is zero if n == 0: raise ValueError("First value cannot be zero") # initialize a list called numbers with the initial input as the first element numbers = [n] # loop while sentinel value is not entered while n != 0: # get user input n = float(input()) # add input to numbers list numbers.append(n) # calculate average by summing all the numbers and dividing by the # number of elements in the list minus 1 # minus 1 because it includes the last zero average = sum(numbers) / (len(numbers) - 1) # print the average print(average)
You can also implement it as a function like this:
def get_average(): # get initial input n = float(input()) # raise ValueError if user initial input is zero if n == 0: raise ValueError("First value cannot be zero") # initialize a list called numbers with the initial input as the first element numbers = [n] # loop while sentinel value is not entered while n != 0: # get user input n = float(input()) # add input to numbers list numbers.append(n) # calculate average by summing all the numbers and dividing by the # number of elements in the list minus 1 # minus 1 because it includes the last zero average = sum(numbers) / (len(numbers) - 1) # return the average return average