Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to average multiple inputs in Python in a condensed form?

I have many, many numbers to write and it is simply not efficient to write out...

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))

...when you have a thousand numbers. So how can I use the range feature maybe to get many numbers from a single input line and then also calculate the mean or average of all of the inputs?

like image 371
Jesse Avatar asked Mar 14 '23 06:03

Jesse


1 Answers

One way is to use a for loop to repeatedly query for the numbers. If only the average is needed, it's sufficient to just increment a single variable and divide by the total number of queries at the end:

n = 10
temp = 0
for i in range(n):
    temp += float(input("Enter a number"))

print("The average is {}".format(temp / n))

By using the built-in sum() function and generator comprehension it's possible to shorten that code alot:

n = 10
average = sum(float(input("Enter a number")) for i in range(n)) / n
print("The average is {}".format(average))
like image 128
Sebastian Hoffmann Avatar answered Mar 23 '23 18:03

Sebastian Hoffmann