Python How To Find The Average Of 10 Numbers Using A While Loop

You can find the average of 10 numbers in Python using a while loop as follows:

# Initialize variables to keep track of the sum and count of numbers
sum_of_numbers = 0
count = 0

# Use a while loop to repeatedly prompt the user for input until 10 numbers are entered
while count < 10:
    try:
        number = float(input(f"Enter number {count + 1}: "))
        sum_of_numbers += number
        count += 1
    except ValueError:
        print("Invalid input. Please enter a valid number.")

# Check if the count is greater than 0 to avoid division by zero
if count > 0:
    average = sum_of_numbers / count
    print(f"The average of the 10 numbers is: {average:.2f}")
else:
    print("No valid numbers entered.")

  • We initialize variables to keep track of the sum and count of numbers.
  • We use a while loop to repeatedly prompt the user for input until 10 numbers are entered.
  • Inside the loop, we attempt to convert the user's input to a floating-point number using float(). If the input is a valid number, we add it to the sum_of_numbers and increment the count. If the input is not a valid number, we print an error message.
  • After the loop, we check if the count is greater than 0 to avoid division by zero, and then we calculate the average by dividing the sum by the count and print the result.