如果输入等于特定数字,如何使用sys.exit

问题描述

我正在寻找更正此代码方法,以便当用户输入99999时该代码停止运行,即时消息也希望将其设置为如果用户输入为999则将总数设置为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()

解决方法

因此,您将输入作为字符串并立即将其转换为int,但实际上您可以稍后将其转换为int并首先检查输入中的某些单词。

现在您拥有

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

但是如果您将其更改为

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

然后我们可以在两者之间添加更多代码

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)

这应该具有预期的效果