开发者

a for loop that won't pass beyond the first item in python

开发者 https://www.devze.com 2023-03-03 05:39 出处:网络
I have this simple average function and when its run with a test data, will show the length of the data, but when calculating the actual average just won\'t go beyond the first item in the sequence.I

I have this simple average function and when its run with a test data, will show the length of the data, but when calculating the actual average just won't go beyond the first item in the sequence. I need help in finding what I am doing wrong here. Thanks in advance for taking the time t开发者_运维问答o answer if you do.

def avg(seq):
    total = 0
    for i in seq:

        total+=i

        average = total/len(seq)
        return (float(average))

test_data = (12,89,90)
print(len(test_data))
print(avg(test_data))


This is wrong:

def avg(seq):
    total = 0
    for i in seq:
        total+=i
        average = total/len(seq)
        return (float(average))

This is right:

def avg(seq):
    total = 0
    for i in seq:
        total += i
    average = total / len(seq)
    return average

Or, if you haven't upgraded to 3.x yet,

average = float(total) / len(seq)


You may consider using standard python functions instead,

>>> seq = (12,89,90)
>>> sum(seq)
191
>>> float(sum(seq))/len(seq)
63.666666666666664


When you put a return in a function, it exits the function completely. Pull your loop to outside of the function, or return a tuple/list outside of the for loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消