-2

I am looking to correct this code so that when the user inputs 99999 then the code stops running, im also looking to make it so that if the user input is 999 it sets the total to 0

import sys

def money_earned():

     total = int()

     try: # try open the file
         file = open("total.txt", "r") 
         data = file.readline()
         total = int(data)
     except: # if file does not exist
         file = open("total.txt", "w+") # create file
         total = 0

     file.close() # close file for now

     while True:
         try:
             pay_this_week = int(input("How much money did you earn this week? "))
             break
         except ValueError:
             print("Oops! That was no valid number. Try again...")

     pay_this_week_message = "You've earned £{0} this week!".format(pay_this_week)
     total = pay_this_week + total
     total_message = "You have earned £{0} in total!".format(total)
     print(pay_this_week_message)
     print(total_message)

     if pay_this_week == "99999":
         sys.exit()

     file = open("total.txt", "w") # wipe the file and let us write to it
     file.write(str(total)) # write the data
     file.close() # close the file

money_earned()
winterwolf
  • 17
  • 2

1 Answers1

0

So you're taking the input as a string and immediately converting it to an int, but you could actually convert it to an int later and check for some words in your input first.

Right now you have

 pay_this_week = int(input("..."))

but if you change this to

input_from_user = input("...")
pay_this_week = int(input_from_user)

then we can add some more code inbetween

input_from_user = input("...")
if input_from_user == "done":
    return  # this will exit the function and so end execution
elif input_from_user == "reset":
    total = 0 # reset the total
else:
    pay_this_week = int(input_from_user)

this should have the desired effect

Jay
  • 2,553
  • 3
  • 17
  • 37