You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python计算器每次操作后均显示重新运行提示?

解决Python文本计算器重复运行提示问题

你的问题出在代码只在首次执行计算器后做了一次重新运行的判断,第二次调用calculator()后没有后续的询问逻辑,所以无法持续触发提示。要实现每次操作后都显示询问,只需要用循环结构来包裹核心逻辑即可。

修改后的完整代码

print("WELCOME TO A TEXT INPUT        BASED CALCULATOR, WRITTEN IN PYTHON!\nREMEMBER, ONLY INPUT YOUR NUMBER, WITHOUT ANY EXTRA CHARACTERS, TO AVOID ERRORS!\nTHANK YOU FOR USING OUR CALCULATOR!\n\n\n")

def calculator():
    print("Select the operation you would like to perform:")
    print("1. ADDITION\n2. SUBTRACTION\n3. MULTIPLICATION\n4. DIVISION\n")

    operation = input()

    if operation == "1":
        num1 = input("\nEnter first number:\n")
        num2 = input("\nEnter second number:\n")
        print("Answer: " + str(int(float(num1) + float(num2))))
    elif operation == "2":
        num1 = input("\nEnter first number:\n")
        num2 = input("\nEnter second number:\n")
        print("Answer: " + str(int(float(num1) - float(num2))))
    elif operation == "3":
        num1 = input("\nEnter first number:\n")
        num2 = input("\nEnter second number:\n")
        print("Answer: " + str(int(float(num1) * float(num2))))
    elif operation == "4":
        num1 = input("\nEnter first number:\n")
        num2 = input("\nEnter second number:\n")
        print("Answer: " + str(int(float(num1) / float(num2))))
    else:
        print("Whoops... Invalid input.")

# 用while循环实现持续运行逻辑
while True:
    calculator()
    print("\n")
    rerunchoice = input("Run another operation? (y/n) ")
    print("\n")
    if rerunchoice.lower() != "y":
        print("Thank you for using our calculator :)")
        break

关键修改说明

  • 用while True创建无限循环,每次循环内先执行计算器操作,再询问用户是否继续。
  • 当用户输入内容(转为小写后)不是"y"时,打印退出提示并通过break终止循环;否则循环自动再次执行计算器操作。
  • 去掉原代码中多余的quit(),用break终止循环更符合Python常规写法。

可选优化建议(非必需)

  • 给数字输入添加异常处理,避免用户输入非数字内容导致程序崩溃,比如用try-except包裹数值转换逻辑。
  • 操作选择部分增加输入验证,提示用户必须输入1-4的有效选项。

内容的提问来源于stack exchange,提问作者user22111357

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:52:58