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
1 Answer 1
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.
1 Comment
nonlocal