Objective
Develop a Python program to calculate various basic statistical operations: it will accept numbers from the user and display their sum, average, minimum, and maximum, as in the following example:
Number? 5
Total=5 Count=1 Average=5 Max=5 Min=5
Number? 2
Total=7 Count=2 Average=3.5 Max=5 Min=2
Number? 0
Goodbye!
(As seen in this example, the program will end when the user enters 0)
Example Python Exercise
Show Python Code
# Initialize variables to store the sum, count, minimum, and maximum
total = 0
count = 0
minimum = None
maximum = None
# Use a while loop to prompt the user for numbers until 0 is entered
while True:
num = float(input("Number? "))
# Check if the entered number is 0
if num == 0:
print("Goodbye!")
break
# Update the total sum and count
total += num
count += 1
# Update the minimum and maximum values
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
# Calculate the average
average = total / count
# Display the current statistics
print(f"Total={total} Count={count} Average={average} Max={maximum} Min={minimum}")
Output
Number? 5
Total=5 Count=1 Average=5.0 Max=5.0 Min=5.0
Number? 2
Total=7 Count=2 Average=3.5 Max=5.0 Min=2.0
Number? 0
Goodbye!
Share this Python Exercise