Variable not being set in function

I am trying to set a variable in a function to false. I have it so the parameters contain the variable I wish to set to false but it always returns as True.

test1 = "item1"
item1 = True
britems = [test1]
inventory = []

def itemtake(item,iflag,roomit):
  if iflag == True:
    print("You take the", item)
    inventory.append(item)
    roomit.remove(item)
    iflag = False
    print(item,"=",iflag)
  else:
    print("Can't take that")

gameIn = input("Take?\n")

if gameIn == "take item1":
  itemtake(test1,item1,britems)
  print(test1,"=",item1)

in the function it prints that item1 = False, but outside of it it prints that it is True.

I’ve tried setting iflag to global but that gave an error, setting a variable to iflag and setting said variable to global, didn’t work.

>Solution :

TL;DR: Return your boolean value from your function, and set it outside:

def itemtake(item,iflag,roomit):
    ...
    return iflag


# Later, when you call the function:
item1 = itemtake(test1, item1, britems) 
# Now item1 is set to what you returned from the function


The global keyword denotes that a name is to be used from the global context. It has nothing to do with the actual value of the variable. Setting a name in a local context (such as inside a function) will only modify it in the current scope, unless that name has been denoted as a global.

You shouldn’t can’t? set or overwrite the value of an argument to a function and have it reflected outside (even with global, since the name of that value inside the function isn’t necessarily the same as the name outside). Consider the following, which throws a SyntaxError:

def foo(bar):
    global bar        # SyntaxError: name 'bar' is parameter and global
    bar = not bar

If it’s a mutable type, you can modify its value (e.g. appending to a list inside the function will persist outside the function). Consider the following snippet:

def foo(bar):
    bar.append("123")

lst = ["abc"]
foo(lst)

print(lst) # ["abc", "123"]

Unfortunately, you’re trying to do this with a boolean value, which is immutable. In this case, you should return that value from your function, and set it where you called the function. Consider the following:

def foo(bar):
    bar = not bar # Sets the value in the local scope
    return bar    # Returns the modified value

boo = True

foo(boo)
print(boo)  # still True, because you never modified the value in the global scope

boo = foo(boo) 
print(boo)  # False, because you set the value of boo in this scope

Leave a Reply