简体   繁体   中英

Why python doesn't exit the script?

I have the following simple python program to find roots of equation with the bisection method:

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

ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command.

Morover, the kernel dies (I'm using jupyter). Can you help me?

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

You should use sys.exit("optional custom message") instead of just exit()

This raises a SystemExit exception, while just exit() only makes sense in the context of the interpreter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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