Python Forum
Simple averaging program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple averaging program
#1
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)
Reply
#2
(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?
Reply
#3
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
Reply
#4
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.
Reply
#5
Ah, statistics. Sure. I was checking the math module. I thought there had to be some sort of average somewhere.
Reply
#6
(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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020