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



嗨,我正在检查图中的循环

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条件来打印某些内容?

使用;尝试";以及";除了";关键字,读取python中的异常处理。

基本上你需要:

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

您在这里寻找的是错误处理。它的工作原理就像if,可以处理您想要的错误。

您可以通过try/except块来实现这一点。更多详细信息请点击此处。

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")

最新更新