0

I'm trying to write a function that recieves any length string of positive or negative whole numbers and adds each number to the total, as long as the value doesn't go below zero. (It returns 0 for any invalid or empty input.)

I'm having trouble writing a loop that re-sets the count to zero when it becomes negative and continutes adding from where it left off.

e.g.
input: 1, 2, -4, 1, 1
output: 2

Here's my code:

def sum_earnings():
values = input("Enter a string of pos &/or neg numbers separated by commas (e.g. 1,-3,0,-4): ").split(',')
earnings = 0

try:
    for i in values:
        earnings += int(i)
        while earnings >= 0:
            earnings += int(i)
        else:
            earnings = 0
            continue
    print(earnings)

except ValueError:
    print(0)

return
4
  • ur indentation is wrong. Commented Oct 10, 2019 at 13:54
  • Thanks, I just noticed that and changed it a bit to correct for unneccesary code. Commented Oct 10, 2019 at 13:56
  • I'm unclear what you want to do - does it produce 0 if the running total ever drops below zero? In which case, why do you need to pick it up again? Also, yes, your indent is wrong there :) Commented Oct 10, 2019 at 13:56
  • Ah, I see now you've added a concrete example :) Commented Oct 10, 2019 at 13:57

1 Answer 1

1

Seems overly complicated. Try the following:

earnings = 0
for i in values:
    try:
        earnings = max(0, earnings + int(i))  # resets to 0 for negative intermediate sum
    except ValueError:
        earnings = 0
        break  # this will end the loop for invalid input
print(earnings)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.