Variable not defined error after defining variable in another function

40 Views Asked by At

My IDE is telling me that the variable multiplied isn't defined:

def multiply():
    surrounding_x()
    
    multiplied = False
    x_index = chars.index("x")
    before_x = chars[x_index - 1]
    after_x = chars[x_index + 1]
    num = 2
    while num <= 50:
        if int(before_x) == num:
            print("X is being multiplied by " + str(num) + ".")
            multiplied = True
            return multiplied

            break
        else:
            num += 1 

    if num  == 50:
        print('X is not being multiplied. ')

Here is where I defined the variable multiplied as True.

def order():
    division()
    addition()
    subtraction()
    multiply()

    if multiplied == True:
        pass
    if division == True:
        pass
    if addition == True:
        pass
    if subtraction == True:
        pass

All of the other variables (division, addition, and subtraction) have similar if not identical syntax defining them.

I tried renaming the variable. I thought that maybe I had made a spelling mistake. I have no idea what could be causing this, so if someone could help that would be awesome. As a beginner programmer, I think the answer to the problem is probably very simple but I don't yet understand it.

1

There are 1 best solutions below

1
fam-woodpecker On BEST ANSWER

Variables exist within a scope, and those variables do not pass between scopes unless you specify them to. Here, in the scope within the function order, there are four functions that exist within this scope, addition, multiply, subtraction, division. Note, these are functions not variables.

As such, you use the variable multiplied within the scope of the function and the scope within order cannot see this variable. Now, division, subtraction, and addition seem to work because you are using the same name as the function, it is not the variable that you are likely trying to access.

You do return your variables within the functions, but you are not storing them as anything in the scope of order. Additionally, if the outputs are boolean, you don't need to write if val == True because that can be the same as if val because val is either True or False.

Try this instead:

def order():
    div = division()
    add = addition()
    sub = subtraction()
    mult = multiply()

    if mult:
        pass
    if div:
        pass
    if add:
        pass
    if sub:
        pass