当列表为null时,Python Try Except



我一直在这里搜索我的问题,但我找不到问题的确切答案。我调用了一个sympy函数(solve(((。此函数可以返回完整列表或空列表。我把这段代码叫做

try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass

我想要的是:如果solve((返回一个空列表,只需通过即可。如果solver((返回完整列表,请继续执行。求解将返回空列表,直到我找到正确的值。这可以通过检查sol[0]来实现,如果有一个非空列表,这将起作用,但如果列表是空的,这将抛出一个错误(空指针(,我想尝试标记它并通过。

我现在看到的是,当sol为空时,它试图获取sol[0][0],而ofc抛出了一个尝试没有捕捉到的错误,整个代码都停止了。有人知道解决这个问题的办法吗?我没有正确使用try?

将每个循环开头的sol设置为某个值,并在except子句中进行检查

关于else

try/except有一个else,它将在try块未引发异常时运行

for有一个else子句,用于未脱离!

for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else:  # did not raise an Exception
break
else:  # did not break out of for loop
raise Exception("for loop was not broken out of!")

最新更新