首页 > 解决方案 > 如果输入等于特定数字,如何使用 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()

标签: pythonexitsys

解决方案


因此,您将输入作为字符串并立即将其转换为 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)

这应该有预期的效果


推荐阅读