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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With