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

Python使用函数实现重复运算无法正常终止如何解决?

问题定位

  • 条件判断逻辑错误:你写的if c == "y" or "Y"不符合Python语法规则,该表达式会被解析为(c == "y") or ("Y"),非空字符串"Y"的布尔值恒为True,所以无论输入什么内容,判断条件永远成立,只会递归调用start()重启流程,不会走到退出分支。正确写法为if c == "y" or c == "Y",或更简洁的if c.lower() == "y"。
  • 退出函数未调用:sys.exit是Python内置函数,执行退出操作需要加括号完成调用,你仅写了sys.exit只是引用了函数对象,没有实际执行退出逻辑,就算走到else分支也不会生效,正确写法为sys.exit()。

修正后代码

import math
import sys
def start():
  t = input()
  x = int(t)
  try:
    a = (3 * math.pow(x, 4) - 12 * math.pow(x, 2) - 1)/((x + 2)*(x - 2))
    b = math.log(8 * x) # 原3*x+5*x可直接简化为8*x

    if a * b < 50:
      f1 = 1 / math.pow(a, 2) - math.pow(a, 2) * b - 11
      print(round(f1, 2))
    else:
      f2 = 16 * a * b - 2 * math.sqrt(2)
      print(round(f2, 2))
  except (ValueError, ZeroDivisionError):
    print("error")

  c = input("repeat?")
  if c.lower() == "y":
    start()
  else:
    sys.exit()
start()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:54:03