【问题标题】:UnboundLocalError: local variable 'start' referenced before assignment [duplicate]UnboundLocalError:分配之前引用的局部变量“start”[重复]
【发布时间】:2021-12-16 18:17:24
【问题描述】:

运行代码时出现错误“UnboundLocalError: local variable 'start' referenced before assignment”

def generateDestinationIP(start, end):
    first = 10
    second = 0; 
    third = 0;

    #eg, ip = "10.0.0.64"
    ip = ".".join([str(first), str(second), str(third), str(randrange(start,end))])

    return ip

    def main(argv):
    #print argv
    
    #getopt.getopt() parses command line arguments and options 
    try:
        opts, args = getopt.getopt(sys.argv[1:], 's:e:', ['start=','end='])
    except getopt.GetoptError:
        sys.exit(2)

    for opt, arg in opts:
        if opt =='-s':
            start = int(arg)
        elif opt =='-e':
            end = int(arg)

    if start == '':
        sys.exit()
    if end == '':
        sys.exit()

如何解决这个问题?

【问题讨论】:

  • 请先提取一个minimal reproducible example,然后在线搜索错误信息。
  • 您的for 循环不一定为start 赋值。如果不存在,则当代码到达if start == '': 测试时,start 不存在。通过初始化start 来修复它。并考虑使用argparse 而不是getopt。这将通过为您进行初始化来防止错误。

标签: python networking anaconda sdn ddos


【解决方案1】:

您的变量 start 只能在 generateDestinationIP 函数内作为其参数访问 - 同样作为 for 循环中的局部变量。您可能希望像这样在 for 循环之前分配它:

start, end = 0, 0
for opt, arg in opts:
    if opt =='-s':
        start = int(arg)
    elif opt =='-e':
        end = int(arg)

【讨论】:

  • 感谢重播,但我应该把这些行放在哪里,因为如果我把它放在 "def generateDestinationIP(start, end):" 之前或之后??
  • 能否请您发送您遇到的错误的描述?
猜你喜欢
  • 2013-02-28
  • 2021-04-02
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
相关资源
最近更新 更多