Program 3: “Running Sum, Product, and Average of Numbers” Create a program that allows a user to input individual numbers until a sentinel is entered. After the user has entered each number, the program prints the sum, product and average of all the numbers, and a message stating whether each is odd, even, or zero. The functionality must be accomplished using loop(s) and ifs, and include the following:
Here's a Python program that meets the requirements you've outlined. The program collects numerical inputs from the user until a sentinel value is entered, calculates the running sum, product, and average, and provides information about whether each of these values is odd, even, or zero.
def program_header():
print("Welcome to the Running Sum, Product, and Average Program!")
print("You can enter numbers continuously until you enter 'exit' to stop.")
def mySum(a, b):
return a + b
def myProduct(a, b):
return a * b
def myAvg(total, count):
if count == 0:
return 0
return total / count
def print_statistics(count, total_sum, total_product, average):
sum_status = "even" if total_sum % 2 == 0 else "odd" if total_sum != 0 else "zero"
product_status = "even" if total_product % 2 == 0 else "odd" if total_product != 0 else "zero"
avg_status = "even" if average % 2 == 0 else "odd" if average != 0 else "zero"
print(f" The sum is {total_sum} and is {sum_status}.")
print(f" The product is {total_product} and is {product_status}.")
print(f" The average is {average} and is {avg_status}.")
def main():
program_header()
total_sum = 0
total_product = 1
count = 0
while True:
user_input = input("Enter a number (or 'exit' to finish): ")
if user_input.lower() == 'exit':
break
try:
number = float(user_input)
except ValueError:
print("Error: Please enter a valid number.")
continue
total_sum = mySum(total_sum, number)
total_product = myProduct(total_product, number)
count += 1
if count > 0:
average = myAvg(total_sum, count)
else:
average = 0
print_statistics(count, total_sum, total_product, average)
if __name__ == "__main__":
main()
Program Header: The program_header
function prints a welcome message to the user.
Custom Functions:
mySum(a, b)
: Returns the sum of two numbers.myProduct(a, b)
: Returns the product of two numbers.myAvg(total, count)
: Returns the average of the total sum divided by the count, with a check to avoid division by zero.Statistics Printing: The print_statistics
function takes the count, total sum, total product, and average, and prints them along with whether they are odd, even, or zero.
Main Function:
print_statistics
function to display the results.Run the program, enter numbers, and when you're done, type 'exit' to see the final statistics. The program will handle invalid inputs gracefully and provide feedback.