python,如何将 if 放入引发错误的函数?

python, How can I put and if to a function that raise an error?

大家好,我正在检查图表中的循环

import networkx as nx
X2 = {"1": ["4"], "2": ["3"], "3": ["2", "4"], "4": ["1", "3"]}
L2 = []
for k,v in X2.items():
    for i in range(len(v)):
        L2.append((k,v[i]))
print(L2)
G = nx.DiGraph(L2)
G = G.to_undirected()

print(type(G))
print(nx.find_cycle(G))

在这种情况下正确地没有循环所以 nx 函数加注:

raise nx.exception.NetworkXNoCycle('No cycle found.')
networkx.exception.NetworkXNoCycle: No cycle found.

如果函数引发错误,我如何设置 If 条件来打印某些内容?

您在这里寻找的是错误处理。对于您想要的错误,它的工作方式类似于 if

您可以使用 try/except 块来实现此目的。更多详情 here.

import networkx as nx
X2 = {"1": ["4"], "2": ["3"], "3": ["2", "4"], "4": ["1", "3"]}
L2 = []
for k,v in X2.items():
    for i in range(len(v)):
        L2.append((k,v[i]))
print(L2)
try:
    G = nx.DiGraph(L2)
    G = G.to_undirected()
    print(type(G))
    print(nx.find_cycle(G))
except:
    print("Error message")

使用“try”和“except”关键字,阅读python中的异常处理。

基本上你需要:

try:
   your_function_call(arguments)
except nx.exception.NetworkXNoCycle as e:
   print("Found the no cycle exception)