Ad

How Can My Program Stop Running When A User's Number Goal Is Met?

- 1 answer

The purpose of my program is for the user to type in a donation goal. When that number goal is met, my program is supposed to stop. After asking the user for a goal, then my program asks for a donation amount and each donation amount adds on to each other leading up to the goal. Finally, after inputting multiple donation amounts, it should add up to the goal.

goal = ''
userDonation = ''
totalAmount = 0
userCashList = []

#asking for end goal
goal = int(input("Some Charity Donation Tracker... Please enter your goal: "))
print("Current Amount: ", totalAmount)

while totalAmount != goal:
  userDonation = int(input("Please Enter Donation Amount: "))
  print("Current Amount: ", userDonation + totalAmount)
  userCashList.append(totalAmount)
  for cash in userCashList:
      totalAmount += userDonation
  if userDonation == goal:
      print("You have met your goal!")
  else:
      userCashList.append(userDonation)

Output:

Some Charity Donation Tracker... Please enter your goal: 100
Current Amount:  0
Please Enter Donation Amount: 200
Current Amount:  200
Please Enter Donation Amount: 300
Current Amount:  500
Please Enter Donation Amount: 200
Current Amount:  1300
Please Enter Donation Amount: 

My donation amounts are adding, but why can't it stop at 100?

Ad

Answer

I'm not sure why you need the userCashList array when you already have totalAmount to display the donations so far. Anyway, I have made several changes to your code and it seems to work fine!

Firstly, while totalAmount != goal will only run if totalAmount is not exactly what goal is. This means that if you hit the goal right on the mark, ie. a user donates 100 with a goal of 100, the code will just pass the while loop without indicating that you have passed the goal.

Here is the new code:

goal = ''
userDonation = ''
totalAmount = 0

#asking for end goal
goal = int(input("Some Charity Donation Tracker... Please enter your goal: "))
print("Current Amount: ", totalAmount)

while True:
  userDonation = int(input("Please Enter Donation Amount: "))
  totalAmount = totalAmount + userDonation
  print("Current Amount: ", totalAmount)
  if totalAmount >= goal:
      print("You have met your goal!")
      break # Break out of the loop when the goal is met

Instead of just running when the total is not equal to the goal, the while loop runs forever. This is stopped by the if statement which checks every increment if the total is equal to or greater than the goal. If so, inform the user and break out of the loop, thus stopping the script.

I am new to answering SO questions, so I hope this helps! :)

Ad
source: stackoverflow.com
Ad