4

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?

Jesse
  • 41
  • 5

2 Answers2

4

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))
Sebastian Hoffmann
  • 2,815
  • 1
  • 12
  • 22
3

A concise way is with a list comprehension.

nums = [float(input('enter number {}: '.format(i+1))) for i in range(100)]

Replace 100 with any range you like. This will create a list of input numbers. You can access the n'th input number with nums[n-1].

Alternatively, you could parse a single input string into a list of floats:

>>> nums = [float(x) for x in input('enter numbers: ').split()]
enter numbers: 1.0 3.14 7.124 -5
>>> nums
[1.0, 3.14, 7.124, -5.0]

I'd prefer that over a lot of prompts.

Finally, if getting the numbers from the command line is an option, you can do it like this

import sys

nums = [float(x) for x in sys.argv[1:]]
print(nums)

Demo:

$ python3 getinput.py 1.0 -5.37 8.2
[1.0, -5.37, 8.2]

To get the mean, issue sum(nums)/len(nums), assuming that your list is not empty.

timgeb
  • 76,762
  • 20
  • 123
  • 145