Newbie101
Newbie101

Reputation: 501

For Loops how to use break

I was completing the Loops exercises on CodeAcademy but couldn't figure out what was wrong with my code

Exercise: Over 9000

My Code

What is wrong with the code, it seems to return None when it should return 9020?

#Write your function here

def over_nine_thousand(lst):
    max_sum = 0
    for i in lst:
        max_sum += i
    sum = 0
    for num in lst:
        sum += num
        if sum > 9000:
            break
            return sum
        elif sum == max_sum:
            return max_sum
    if len(lst) == 0:
        return 0


#Uncomment the line below when your function is done

print(over_nine_thousand([8000, 900, 120, 5000]))

Is there a better way to go about doing this?

Upvotes: 0

Views: 85

Answers (2)

Professor Fritz
Professor Fritz

Reputation: 31

You do a break before the return. Use:

   if sum > 9000:
         return sum

 # // 
 if sum > 9000:
        break # Breaks from the for loop
        return sum # This line code will never reached

Upvotes: 3

Austin
Austin

Reputation: 26039

Because you asked for a better way to solve your problem:

def over_nine_thousand(lst):
    total = 0
    for x in lst:
        total += x
        if total > 9000:
            return total
    return total

print(over_nine_thousand([8000, 900, 120, 5000]))

This iterates through list, adding up values and once it sees the added up value is greater than 9000, a return is fired.

The return at the end of loop also handles case if an empty list is passed

Upvotes: 4

Related Questions