# Calculate average of random amount of numbers entered by user python

Calculating the average of a random amount of numbers entered by the user in Python can be achieved in different ways. In this article, we will explore three different solutions to this problem.

## Solution 1: Using a List

In this solution, we will use a list to store the numbers entered by the user. We will keep accepting numbers until the user enters a non-numeric value. Then, we will calculate the average by summing up all the numbers in the list and dividing it by the length of the list.

``````numbers = []
while True:
try:
number = float(input("Enter a number (or any non-numeric value to stop): "))
numbers.append(number)
except ValueError:
break

average = sum(numbers) / len(numbers)
print("Average:", average)``````

## Solution 2: Using a Counter

In this solution, we will use a counter to keep track of the number of values entered by the user. We will also use a running total to calculate the sum of all the numbers. We will keep accepting numbers until the user enters a non-numeric value. Finally, we will calculate the average by dividing the running total by the counter.

``````total = 0
counter = 0

while True:
try:
number = float(input("Enter a number (or any non-numeric value to stop): "))
total += number
counter += 1
except ValueError:
break

average = total / counter
print("Average:", average)``````

## Solution 3: Using a Generator

In this solution, we will use a generator to calculate the average. We will define a function that accepts numbers from the user until a non-numeric value is entered. The function will yield each number, and we will use the built-in sum() function to calculate the sum of all the numbers. Finally, we will divide the sum by the number of values entered to obtain the average.

``````def get_numbers():
while True:
try:
number = float(input("Enter a number (or any non-numeric value to stop): "))
yield number
except ValueError:
break

numbers = list(get_numbers())
average = sum(numbers) / len(numbers)
print("Average:", average)``````

After analyzing the three solutions, it can be concluded that Solution 1, which uses a list, is the better option. It is more concise and easier to understand compared to Solution 2 and Solution 3. Additionally, using a list allows for more flexibility in further processing the numbers if needed.

Rate this post

### 3 Responses

1. Chloe Walker says:

Solution 3: Using a Generator seems intriguing, but how does it compare to the other two?

1. Zain Sanford says:

Ive tried all three solutions and the Generator is by far the most efficient. It saves time and effort, allowing you to focus on more important tasks. Trust me, once you give it a shot, you wont look back.

2. Annie Jaramillo says:

I never thought Id enjoy reading about average calculations, but this article nailed it! Solution 3 using a generator sounds pretty cool.