Python Forum
Intializing return value to 0
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Intializing return value to 0
#1
Hey guys, the problem is asking the following:

Use the Design Recipe to write a function called running_average that repeatedly asks the user to input integers at the keyboard until they type the word done. Return the average of the values they entered. You may assume the user will only enter integers or "done". Include a docstring!

Note: You do not need to provide assertEqual statements for this function.
For example:

Test
Input
Result
print(running_average()
3
5
done
4

The following is my code:
def running_average():
    running_average = input("Enter an interger")
    total=0
    num=0
    
    while running_average !="done":
        total=int(running_average) + total
        num += 1
        running_average=input("Enter an integer")
        if num == 0:
            return 0
        else:
            running_average=total/num
            return running_average
            
But I keep getting the following error :
Incorrect - you should initialize your return value to 0

I have no idea what I did wrong. Thanks for the help
Reply
#2
The variable num is never 0 on line 10, because you add one to it on line 8. So you never return 0. Furthermore, if 'done' is the first response, the while loop doesn't run, and you return the default of None. Note that your return statement should be after the while loop. Right now the program returns after the second thing entered, no matter what.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
This is a pretty choppy way to do this but I'm not sure why you set the value of num to 0 and then added 1 to it before even checking to see if it equals to 0 first. I rewrote what I (think?) you originally meant:

def running_average():
    total = 0
    num_values = 0
    average = 0
    while True:
        value = input("Enter an integer: ")

        if value == "done":
            break
        else:
            total += int(value)
            num_values += 1
            average = total / num_values
    return average


#print(running_average())
When it says you should initialize your return value to 0, it doesn't mean to literally return 0, but instead, you see how you're returning running_average? What it means is in your first declaration of running_average, you should set it to 0.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020