简体   繁体   English

为什么python不退出脚本?

[英]Why python doesn't exit the script?

I have the following simple python program to find roots of equation with the bisection method:我有以下简单的 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")

If I put a in the wrong interval (like a=3) it says that it's the wrong interval, but it continues anyway giving (obviously) a wrong result and four lines of如果我把 a 放在错误的区间(如 a=3),它说这是错误的区间,但它仍然继续给出(显然)错误的结果和四行

ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command. ERROR:root:Invalid alias: the name less 不能被别名,因为它是另一个神奇的命令。

Morover, the kernel dies (I'm using jupyter). Morover,内核死了(我正在使用 jupyter)。 Can you help me?你能帮助我吗?

这可能是因为您需要在 if 语句完成后添加一个 else 语句来说明它是否为 false 执行此操作,否则执行其余代码。

You should use sys.exit("optional custom message") instead of just exit()您应该使用sys.exit("optional custom message")而不是exit()

This raises a SystemExit exception, while just exit() only makes sense in the context of the interpreter.这会引发SystemExit异常,而exit()仅在解释器的上下文中才有意义。

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

The difference is described in detail here!区别在这里详细描述! https://stackoverflow.com/a/19747562/4541045 https://stackoverflow.com/a/19747562/4541045

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM