Python Forum

Full Version: Can a function modify a variable outside it?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can get a for loop or while loop to modify a variable outside them, but I can't figure out how to get a function to do that.

# THIS WORKS
list_len = 0

while list_len < 100:
    list_len += 1

print(list_len)
# THIS DOES NOT WORK
list_len = 0

def list_inc():
    list_len += 1

list_inc()

# UnboundLocalError: local variable 'list_len' referenced before assignment
(Jul-29-2019, 11:48 PM)Exsul Wrote: [ -> ]I can get a for loop or while loop to modify a variable outside them, but I can't figure out how to get a function to do that.

# THIS WORKS
list_len = 0

while list_len < 100:
    list_len += 1

print(list_len)
# THIS DOES NOT WORK
list_len = 0

def list_inc():
    list_len += 1

list_inc()

# UnboundLocalError: local variable 'list_len' referenced before assignment

Maybe you will read about global variables note that is bad, I will suggest you not use global variables, you can do it like

list_len = 0

def list_inc(list_):
    return list_ +1

list_len = list_inc(list_len)
I'm very new to programming. Why are global variables bad, and what should I use instead?
(Jul-30-2019, 12:11 AM)Exsul Wrote: [ -> ]I'm very new to programming. Why are global variables bad, and what should I use instead?

Read about global variables http://wiki.c2.com/?GlobalVariablesAreBad
This is your code using global variable *workable

# THIS NOW WORK SEE THE LINE 2

def list_inc():
    global list_len
    list_len += 1
 
list_inc()
To avoid using local variable you can use

list_len = 0
 
def list_inc(list_):
    return list_ +1
 
list_len = list_inc(list_len)