0
def a():
    b = 1
    def x():
        b -= 1
    if something is something:
        x()
a()

What im wanting here is to change b from a() in x() I have tried using;

def a():
    b = 1
    def x():
        global b
        b -= 1
    if something is something:
        x()

a()

But this, as I expected, this told me global b is not defined.

b needs to change after x() is has run and if x() is called a second time b needs to be what x() set it to - 0 not what it was originally set to in a() - 1.

2 Answers 2

3

In order to alter the value of a variable defined in a containing scope, use nonlocal. This keyword is similar to intent to global (which indicates the variable should be considered to be the binding in the global scope).

So try something like:

def a():
    b = 1
    def x():
        # indicate we want to be modifying b from the containing scope
        nonlocal b
        b -= 1
    if something is something:
        x()

a()
Sign up to request clarification or add additional context in comments.

2 Comments

Could you elaborate at all on what non local is exactly. Very new to Python (well programming in general)
Than you, that explanation was perfect
1

This should work:

def a():
    b = 1
    def x(b):
        b -= 1
        return b
    b = x(b)
    return b
a()

1 Comment

Thanks but I was hoping for a way to do it without using 'return'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.