Home > Back-end >  python function only works when value is global
python function only works when value is global

Time:12-04

when i do

def togglesize():
    global is_small
    
    if is_small == True:
        notsmall()
        is_small = not is_small
    elif is_small == False:
        makesmall()
        is_small = not is_small

it works, but when i do this

def togglesize():
    is_small = True
    
    if is_small == True:
        notsmall()
        is_small = not is_small
    elif is_small == False:
        makesmall()
        is_small = not is_small

it doesn't work

why does it only work when global?

CodePudding user response:

If you want to modify the variable is_small outside of the scope of the function, you can pass it as an argument and return its new value. You probably don't need to use a global variable.

def togglesize(is_small):
    if is_small == True:
        notsmall()
        is_small = not is_small
    elif is_small == False:
        makesmall()
        is_small = not is_small
    return is_small

If you call your function like this:

is_small = togglesize(is_small)

This will modify is_small from True to False or False to True.

CodePudding user response:

With this line is_small = True you are setting is_small to True every time you call the function. This part

        notsmall()
        is_small = not is_small

gets executed every time you call the function. The rest never runs.

Edit: Also, in your second example is_small is discarded when the function ends. So it does not matter what value you set it to. If you want it to persist, you need to make it available outside the function. Adding global does that.

  • Related