Updating/Modifying a variable inside a function

Viewed 41

I'm trying to modify a variable inside of a function. But while I can print out the variable (so access it) I cant seem to modify it.

Is there a simple solution for this or am I doing it all wrong?

Code:

a_number = 500

def a_function():
    print(a_number)
    a_number -= 100
    print(a_number)

a_function()

I want to be able to have the function lower the value of "a_number" with 100. But it gives me this error:

UnboundLocalError: local variable 'a_number' referenced before assignment

1 Answers

You can use the global key in you a_function.

a_number = 500

def a_function():
    global a_number
    print(a_number)
    a_number -= 100
    print(a_number)


a_function()

It tells the function to treat a_number as a global var instead that can be modified inside the function.

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Related