Nov-16-2023, 06:16 AM
This works as YOU would expect.
This is going to surprise you.
And for completeness:
a = 42 def func(): return a print(func())
Output:42
Because a is not assigned a value in func(), the function does not create a local "a" variable and the "a" used in func() is the a from the global scope (a = 42)This is going to surprise you.
a = 42 def func(): a = "Hi Mom" print("a inside func =", a) func() print("a outside func =", a)
a inside func = Hi Mom a outside func = 42Here we have two variables named "a"; on in the global scope (a = 42) and one in the function scope (a = "Hi Mom"). func() does not use the global "a" because func() assigns a value to "a" it creates its own "a" variable.
And for completeness:
a = 42 def func(): global a a = "Hi Mom" print("a inside func =", a) func() print("a outside func =", a)
Output:a inside func = Hi Mom
a outside func = Hi Mom
In this example there is only one variable named "a". The "global a" inside func() tells python to use "a" from the global scope instead of creating a local variable.