2

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?

Ravi Kumar Gupta
  • 1,698
  • 2
  • 22
  • 38
MKF
  • 49
  • 1
  • 9
  • Please extract a [mcve] first and search for the error message online. – Ulrich Eckhardt Nov 02 '21 at 07:28
  • Your `for` loop does not necessarily assign a value to `start`. When it does not, `start` doesn't exist when the code reaches the `if start == '':` test. Fix it by initializing `start`. And consider using `argparse` instead `getopt`. That would have forestalled the error by doing the initialization for you. – BoarGules Nov 02 '21 at 07:33

1 Answers1

1

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)
ArtFul
  • 21
  • 6
  • Thanks for replay but where I should put these lines as I have some errors in case I put it before "def generateDestinationIP(start, end):" or after it ?? – MKF Nov 02 '21 at 07:55
  • Could you please send the description of errors you get? – ArtFul Nov 02 '21 at 07:59