Write a program that repeatedly asks for numbers. When the user enters 0, the program prints the average of all numbers entered (excluding the 0) accurate to two decimal places and exits.
Question
Write a program that repeatedly asks for numbers. When the user enters 0, the program prints the average of all numbers entered (excluding the 0) accurate to two decimal places and exits.
Solution
Here is a simple Python program that accomplishes this task:
# Initialize variables
total = 0
count = 0
# Start a loop that will continue until the user enters 0
while True:
# Ask the user for a number
num = float(input("Enter a number (0 to end): "))
# If the user entered 0, break the loop
if num == 0:
break
# Otherwise, add the number to the total and increment the count
total += num
count += 1
# Calculate the average
average = total / count
# Print the average, formatted to 2 decimal places
print("Average of all numbers entered: {:.2f}".format(average))
This program works by keeping a running total of all numbers entered, as well as a count of how many numbers have been entered. When the user enters 0, it calculates the average by dividing the total by the count, and then prints this average rounded to two decimal places.
Similar Questions
In this exercise you will create 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.
Write a program that reads in a number (integer) as input, adds 1 to it, and then prints out the result. Here is an example interaction between your program and the user:Please enter a number: 34
Problem StatementWrite a program to find the average of N numbers. Print the average in 2 digit precision DO NOT USE ARRAYInput FormatFirst line consist of a single integer - 'N'Second line consist of N space separated integersOutput FormatDisplay the average of N numbersSample Input51 2 3 4 5Sample Output3.00
Initialize an array/list with five integers. Write a program to find the sumand average of these numbers
Create a program to calculate the sum of numbers entered by the user. The program should ask the user "How many numbers do like to get their sum?:". According to user's answers, use for loop to read integer numbers from the user and display their sum. Refer to the examples below.Use the following two lines of code at the beginning of your answer:print("How many numbers do like to get their sum?:")nums=int(input())sum = 0
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.