UnboundLocalError: local variable 'divide' referenced before assignment

Question:

This program is designed to be fed a number and generate all of it’s prime factors.
I had this working without using any functions earlier, but now I am trying to implement them to get more functionality in my program.

divide = 2
factors = []

def nextNumber():
    userInput = input("enter a number to generate factors:n") #
    number = int(userInput) 

    half = (number / 2) 
    halfFixed = int(half) 

    for x in range (0, halfFixed): # make second arg half of user number 
        result = number % divide

        if result == 0:
            factors.append(divide)

        divide +=1

nextNumber()
print (factors)

When I try to run it, the input command is read and I can input a number but as soon as I do I get the error, “UnboundLocalError: local variable ‘divide’ referenced before assignment”
Any help at all would be great thanks.

Asked By: Benjamin Cox

||

Answers:

You are assigning to divide in your function, making it a local variable:

divide +=1

Any other use of divide before it is first assigned a value will then raise the UnboundLocal exception.

If you meant it to be a global, tell Python so with the global keyword:

def nextNumber():
    global divide

    userInput = input("enter a number to generate factors:n") #
    number = int(userInput) 

    half = (number / 2) 
    halfFixed = int(half) 

    for x in range (0, halfFixed): # make second arg half of user number 
        result = number % divide

        if result == 0:
            factors.append(divide)

        divide +=1
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.