Reputation: 501
I was completing the Loops exercises on CodeAcademy but couldn't figure out what was wrong with 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
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
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