Python 3.x 在几次干净的运行后,会看到UnboundLocalError

Python 3.x 在几次干净的运行后,会看到UnboundLocalError,python-3.x,Python 3.x,我在随机时间看到unboundlocalerror。你能告诉我怎么解决这个问题吗 def find_switch_and_port_cis(wwn): with open('zones_list.txt') as fin: for line in islice(dropwhile(lambda L: wwn not in L, fin), 1, 15, 1): if 'connected interface' in line:

我在随机时间看到unboundlocalerror。你能告诉我怎么解决这个问题吗

def find_switch_and_port_cis(wwn):
    with open('zones_list.txt') as fin:
        for line in islice(dropwhile(lambda L: wwn not in L, fin), 1, 15, 1):
            if 'connected interface' in line:
                interface = re.findall(':(\S+)', line)
            elif 'switch name' in line:
                switch_name = re.findall(':(\S+)', line)
        print(wwn, ' is connected to interface:' , interface[0], ' on switch:', switch_name[0])

find_switch_and_port_cis(wwn)
该代码给出预期输出:

50:01:43:80:01:1b:42:f6  is connected to interface: fc2/17  on switch: c3-cs9513-02
几次跑步后,但几次跑步后,它会抛出:

UnboundLocalError: local variable 'interface' referenced before assignment

如果您的
for
循环有0次迭代,或者您从未输入
If
子句,则无法打印
接口
变量的值,因为它从未声明过。这是否回答了您的问题?