55.4k views
1 vote
Average Calculator Write a Python program that prompts the user to enter a series of numbers until they enter a negative number.

The program should then calculate the average of the positive numbers entered and display the result to the user. Requirements
- The program should use a while loop to prompt the user to enter a series of numbers until a negative number is entered.
- The program should keep track of the running total of positive numbers entered and the count of positive numbers entered.
- The program should calculate the average of the positive numbers entered using the formula average = sum / count.
- The program should display the average to the user in a user-friendly message.
Hints
- You can use the input() function to prompt the user to enter a number.
- You can use the int() function to convert the user input from a string to an integer.
- You can use a while loop with a condition that checks if the user input is not negative.
- You can use an if statement inside the loop to check if the user input is positive.
- You can use two variables, one to keep track of the running total of positive numbers entered and one to keep track of the count of positive numbers entered.
- You can use an if statement after the loop to check if any positive numbers were entered, and if so, calculate the average and display it to the user.

User RufusInZen
by
8.4k points

1 Answer

5 votes

Final answer:

The Python program uses a while loop to prompt the user for numbers, terminating when a negative number is entered. It then calculates and displays the average of the positive numbers. The process involves using input(), int(), while loop, and if statements.

Step-by-step explanation:

Python Average Calculator Program

To write a Python program that calculates the average of a series of numbers until a negative number is entered, the following approach can be used. A while loop will prompt the user for input and will terminate when a negative number is provided. The program will keep track of the sum of all positive numbers and the count of how many positive numbers have been entered to compute the average.

Here is a sample code:

sum_of_positive_numbers = 0
positive_number_count = 0

while True:
number = int(input("Enter a number (or a negative number to stop): "))
if number < 0:
break
sum_of_positive_numbers += number
positive_number_count += 1

if positive_number_count > 0:
average = sum_of_positive_numbers / positive_number_count
print(f"The average of the positive numbers entered is {average}")
else:
print("No positive numbers were entered.")

The program uses input() to receive numbers, and int() to convert them from strings to integers. The sum and count variables keep track of the accumulated values, and once the loop ends, the program checks if any positive numbers were entered before proceeding to calculate and display the average.

User Antarus
by
8.1k points