Hey so Im a beginner, and I need some help.

My professor gave us this code:

def average(list):
total = 0.0
for number in list:
total += number
return total / len(list)

Then, he asked us to rewrite that program so that it uses a while loop instead.
So far I tried and got this...

def average(list):
total = 0.0
i = 0
while (I < len(list)):
total += list
i += 1
return i

When I tried to run that, I kept getting the wrong answer for any list I tried. :/

If you could please help me, i'd be forever grateful :D

Edited 5 Years Ago by mkbear: n/a

Why completely different return statement? You should push CODE before pasting code, if you like others to read your code and understand it.

Edited 3 Years Ago by happygeek: fixed formatting

You should not use "i", "l", or "O" for variable names as they can look like digits as well as other letters. This code is a good example of why. You will have to discover the problem yourself (the problem may be caused by being too lazy to key in the extra letters), but the following code works for some reason whereas yours does not.

list_in = range(1, 10)
total=0
ctr=0
while (ctr < len(list_in)):
    total += list_in[ctr]
    ctr += 1
print total

Edited 5 Years Ago by woooee: n/a

Everyone is making this way to complicated here is the program working in whole with a list it will do everything you want and is simple.

def average(li):
    total = 0
    i = 0
    while (i < len(li)):
        total += i
        i += 1
        print i

t = ['1', '2', '3', '4', '5']

average(t)
This question has already been answered. Start a new discussion instead.