![]() |
Simple averaging program - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Simple averaging program (/thread-3578.html) |
Simple averaging program - Iskuss - Jun-05-2017 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) RE: Simple averaging program - micseydel - Jun-05-2017 (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? RE: Simple averaging program - nilamo - Jun-07-2017 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 RE: Simple averaging program - micseydel - Jun-07-2017 Or, in Python 3.4+ https://docs.python.org/3/library/statistics.html#statistics.mean The built-in one handles iterators, so isn't reliant on len. RE: Simple averaging program - nilamo - Jun-07-2017 Ah, statistics. Sure. I was checking the math module. I thought there had to be some sort of average somewhere. RE: Simple averaging program - Mekire - Jun-09-2017 (Jun-07-2017, 06:40 PM)micseydel Wrote: Or, in Python 3.4+Had no clue that had been added. That is awesome. |