python - 为什么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)。你能帮助我吗?
解决方案
你应该使用sys.exit("optional custom message")
而不是仅仅exit()
这引发了一个SystemExit
例外,而仅exit()
在解释器的上下文中才有意义。
import sys
# logic here
if "something bad":
sys.exit("optional custom message")
推荐阅读
- docker - 无法从谷歌云构建访问 pip 主机
- android - Flutter App 构建发布问题(Firestore)
- sapply - 在 sapply 中访问向量的先前值
- ios - 应用因隐私而被应用商店拒绝 - 数据收集和存储
- java - 如何在java中使用密钥接口作为密钥?
- assembly - SPARC v8:本地寄存器使用
- python - 如何使用套接字编程将字典数据从客户端发送到 python 服务器以与 df2 进行比较?
- go - Golang 中的 Google Pay PaymentMethodTokenRecipient 函数实现
- sql - 选择每组中除最大记录外的所有记录
- testing - grabAttributeFrom() 方法不返回属性值