首页 > 解决方案 > 为什么python不退出脚本?

问题描述

我有以下简单的 python 程序来使用二分法查找方程的根:

from numpy import exp
#
def fun(x):
  return 5.0+4.0*x-exp(x)
#
a=3
b=10.0
eps=1.0e-15
#
fa=fun(a)
fb=fun(b)
#
if fa*fb>0:
  print("wrong interval!!!",fa,fb)
  exit()
#
iter=1
while (b-a)>eps:
  c=(a+b)/2.0
  fc=fun(c)
  if fc==0:
    print("x = ",c)
    exit()
  if fc*fa>0:
    a=c
    fa=fc
  else:
    b=c
    fb=fc
  iter+=1
#
print("x = ",c)
print("accuracy = ",'{:.2e}'.format(b-a))
print("f(",c,") =",fun(c))
print(iter," iterations needed")

如果我将 a 放入错误的区间(如 a=3),则表示这是错误的区间,但无论如何它会继续给出(显然)错误的结果和四行

ERROR:root:Invalid alias: 名称 less 不能使用别名,因为它是另一个魔术命令。

Morover,内核死了(我正在使用jupyter)。你能帮助我吗?

标签: pythonexitbisection

解决方案


你应该使用sys.exit("optional custom message")而不是仅仅exit()

这引发了一个SystemExit例外,而仅exit()在解释器的上下文中才有意义。

import sys
# logic here
if "something bad":
    sys.exit("optional custom message")

区别在这里详细描述!https://stackoverflow.com/a/19747562/4541045


推荐阅读