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

Python计算器代码输入n后无法回到开头重新循环的问题求助

问题原因

你的代码仅在calculation()函数内部实现了基于当前计算结果连续运算的循环逻辑,当用户输入n时,只会终止函数内部的循环,外层没有任何控制逻辑重新触发计算流程,因此程序会直接终止运行。

修复方案

我们可以新增外层主循环控制程序的启停,同时调整输入提示逻辑匹配需求,修改后代码如下:

from art import logo
from calc_functions import add, subtract, divide, multiply

print(logo)

operations = {
    '+': add,
    '-': subtract,
    '*': multiply,
    '/': divide
}


def calculation():
    num1 = float(input('输入第一个数字:'))
    for symbol in operations:
        print(symbol)
    loop = True

    while loop:
        symbol1 = input('选择要使用的运算符号:')
        num2 = float(input('输入另一个数字:'))
        result = operations[symbol1](num1, num2)
        print(f'{num1} {symbol1} {num2} = {result}')
        reentry = input('是否继续基于当前结果运算?输入 "y" 继续,输入 "n" 开启全新计算,输入 "q" 退出程序:').lower()
        if reentry == 'y':
            num1 = result
        else:
            loop = False
            return reentry

# 外层主循环控制程序启停
while True:
    user_choice = calculation()
    if user_choice == 'q':
        break

修改说明

  • 为calculation()函数新增返回值,传递用户的最终操作选择
  • 新增外层无限循环,当用户输入n时,会自动重新调用calculation()回到程序入口,开启全新的计算流程
  • 仅当用户主动输入q时,才会终止整个程序运行
  • 调整了提示文案为中文,避免用户对操作选项产生歧义

如果不需要额外的退出确认,只要输入n就直接重启计算,也可以用简化修改方案,仅替换原代码最末尾的calculation()调用部分即可:

while True:
    calculation()

内容的提问来源于stack exchange,提问作者Simón Rieta Saldaña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:45:03