UnboundLocalError: local variable 'start' referenced before assignment

Viewed 1113

I have error "UnboundLocalError: local variable 'start' referenced before assignment" when run the code

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

How to fix this?

1 Answers

Your variable start is only reachable inside generateDestinationIP function as its argument - and likewise as a local variable in the for loop. You might want to assign it before the for loop like this:

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