Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

python - How to use sys.exit() if input is equal to specific number

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...