190k views
0 votes
Using a while loop, write a Python program that does the following:

- Ask the user to enter 5 number.
- Calculate and prints the average of the 5 given numbers. .
While loop statement should be used for this assignment. Otherwise no points will be given to the code. File naming direction: Name your code file: YourLastName_hw06.py
Sample run:
Enter a number: 43
Enter a number: 25
Enter a number: 21
Enter a number: 78
Enter a number: 93
52.0 is the average of the given numbers

1 Answer

0 votes

Final answer:

The Python program requested uses a while loop to prompt the user for 5 numbers, calculating and printing the average of those numbers. The program adds each input number to a running sum, counts the number of inputs with a counter, and divides the sum by 5 to get the average after the loop completes.

Step-by-step explanation:

Python Program to Calculate the Average of Five Numbers using a While Loop

To write a Python program that asks a user to enter 5 numbers and calculate the average using a while loop, follow these steps:

  • Initialize a sum variable to 0.
  • Initialize a counter at 0.
  • Use a while loop to iterate until the counter reaches 5.
  • Within the loop, prompt the user for a number and add it to the sum.
  • Increment the counter by 1 after each iteration.
  • After the loop, divide the sum by the number of inputs (5) to get the average.
  • Print the average.

Here is an example code snippet:

sum_of_numbers = 0
counter = 0
while counter < 5:
number = float(input("Enter a number: "))
sum_of_numbers += number
counter += 1
average = sum_of_numbers / 5
print(f"{average} is the average of the given numbers")

Ensure to save your file as YourLastName_hw06.py to follow the file naming direction provided by your instructor.

User Szymon Rozga
by
8.0k points