Python simple loop of averages only returns first item

Question:

I wrote a code to calculate an average, but it takes only the first item in the list.
I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the average.

def average_price_petrol(**args):
result = 0
total = 0
for key,value in args.items():
        result += value
        total +=1
        return result/total

average_price_petrol(aral = 1.799, bft = 1.629, esso = 1.799, shell = 1.829, jet = 1.719)
Asked By: Max

||

Answers:

You need to indent the code properly.

def average_price_petrol(**args):
    result = 0
    total = 0
    for key,value in args.items():
        result += value
        total +=1
    return result/total

Python uses spaces to determine scopes so your code would loop through the first argument and then return the average before the loop has finished

Answered By: m_j_alkarkhi

In addition to the already mentioned indentation issue for return which causes the function to return on the very first loop iteration, you do not need to iterate over args.items() as you don’t care about the keys.

def average_price_petrol(**args):
    result = 0
    total = 0
    for value in args.values():
        result += value
        total += 1
    return result / total

And this can be simplified to:

def average_price_petrol(**args):
    return sum(args.values()) / len(args)
Answered By: Chris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.