python - 如果输入等于特定数字,如何使用 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)
这应该有预期的效果
推荐阅读
- javascript - 一个 js 函数在按钮上创建 9 个不同的警报
- c++ - gradle externalNativeBuild 不接受 cmake INTERFACE 库
- python - 将 GUI 与 wxpython 集成时的代码结构是什么
- makefile - Makefile,所有规则模式的规则
- python - 列不存在(SQLAlchemy / PostgreSQL):引号有问题
- r - R包mrmre分数计算与提取
- python - 需要 Pyspark/Pandas 脚本来实现所需的结果
- wordpress - 如何使用 ACF 块实现 2 列布局
- android - “不接受包 Android SDK Build-Tools 30.0.2 的许可证”
- python - 如何在具有列条件值的数据框中使用 qcut