YourFriend
YourFriend

Reputation: 410

Return inside a loop- How would I make sure it's outside of the loop?

Hey there fellow members, hope you're having a great day, I'm working on an assignment for my class, and I am having an issue. I have to calculate the average in one function and then call it in another function. From my understanding of the textbook (teacher has no idea how to teach), adding "return average" should allow me to use that output in another function right? Well when i run my code, it immediatly returns the average only after 1 input.

I am assuming because "return average" is inside the loop "for test in range" right? If so, I am not sure on how to make it happen outside of that loop(while within that same method), I've tried different ways with no success.

I'd Like some insight on this issue. I appreciate any help I recieve. Thank you!

#variables for amount of scores 
num_of_scores = 5

def calc_average():
    total = 0.0
    for test in range(num_of_scores):
        print('Please enter the score of test', str(test +1), end='')
        score = float(input(':'))
        total += score
        average = total / num_of_scores
        return average
def main():
    average = calc_average()
    print('Average of test scores is', average)

#def determine_grade():
#    if average < 60

main()

Upvotes: 0

Views: 59

Answers (1)

Kobi K
Kobi K

Reputation: 7931

Solution:

The problem lay in your indention, you are looping over num_of_scores and doing sum, the avg calculation and return value of the method need be a part of the method and not a part of the for loop.

#variables for amount of scores 
    num_of_scores = 5

    def calc_average():
        total = 0.0
        for test in range(num_of_scores):
            print('Please enter the score of test', str(test +1), end='')
            score = float(input(':'))
            total += score
        average = total / num_of_scores
        return average

    def main():
        average = calc_average()
        print('Average of test scores is', average)

    #def determine_grade():
    #    if average < 60

    main()

Output:

('Please enter the score of test', '1') :5
('Please enter the score of test', '2') :6
('Please enter the score of test', '3') :7
('Please enter the score of test', '4') :8
('Please enter the score of test', '5') :9
('Average of test scores is', 7.0)

Upvotes: 1

Related Questions