1

Below, I would like the s var be global to the f function, but local to the principal function.

It seems global means "The Most Global in the Module". How can I make one less global scope ?

s="what the hell"
print(s)

def principal():
    s ="hey"
    def f():
        global s 
        if len(s) < 8:
            s += " !"
            f()

    f()
    return s
print(principal())

what the hell
hey
0

1 Answer 1

3

I'm not sure if this is what you are going for, since global has an unambiguous meaning in Python. If you want to modify the variable s as defined in principal() within f() you can use nonlocal:

s="what the hell"
print(s)

def principal():
    s = "hey"
    def f():
        nonlocal s 
        if len(s) < 8:
            s += " !"
            f()

    f()
    return s
print(principal())

But the real goal here would probably be, to avoid constructs like that altogether and pass the respective variables as arguments and return the modified values from (pure) functions.

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

1 Comment

Oh I didn't know nonlocal

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.