Python Forum

Full Version: Simple averaging program
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Probably the most convoluted way to find the average of a set of numbers in Python but here it is.

amount = int(input("Enter number of items: "))#Gets amount of numbers to be averaged
q = "q"
for x in range(1, amount):#This generates as many variables as there are numbers to be averaged
       q = str(x) + q
q = list(q)
for x in range(0, amount):#This sets each variable to the user's input
       q[x] = input("Enter number: ")
sum = 0
for x in range(0, amount):#This finds the sum of all the numbers
       sum = int(q[x]) + sum
average = sum / amount#This finds the average by dividing the sum and the total amount of numbers
print(average)
(Jun-05-2017, 03:07 AM)Iskuss Wrote: [ -> ]Probably the most convoluted way to find the average of a set of numbers in Python but here it is.
Why not do it in a clean, straightforward way?
So many for loops, just use sum(items)/len(items).

>>> amount = int(input("Enter number of items: "))
Enter number of items: 4
>>> q = [int(input("Enter number: ")) for _ in range(amount)]
Enter number: 8
Enter number: 4
Enter number: 1
Enter number: 5
>>> q
[8, 4, 1, 5]
>>> average = sum(q) / len(q)
>>> average
4.5
Or, in Python 3.4+ https://docs.python.org/3/library/statis...stics.mean
The built-in one handles iterators, so isn't reliant on len.
Ah, statistics. Sure. I was checking the math module. I thought there had to be some sort of average somewhere.
(Jun-07-2017, 06:40 PM)micseydel Wrote: [ -> ]Or, in Python 3.4+
https://docs.python.org/3/library/statis...stics.mean
The built-in one handles iterators, so isn't reliant on len.
Had no clue that had been added. That is awesome.