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

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

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

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.