Variable scope in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Variable scope in Python

I've lost it with variable's scope. It seems too odd that wrap() "sees" the func arg because wrap() takes no args. So to make clear, in Python, when we declare one var, we can use it wherever we want after that??

8th Feb 2017, 1:39 AM
Dimitris Skoufis
Dimitris Skoufis - avatar
2 Answers
+ 1
If you declare a variable inside a function, its scope is inside this function making it not reacheable from outside. If you leave this function and call it again later on, the variable will be redefined. The only way to keep a local variable for outside of the function use is by using the return statement (or yield..) If you declare a global variable it can always be accessed as its scope isnt limited. The reasons you dont make every variable global are: easier to read code and better usage of resources i.e. memory.
28th Feb 2017, 1:21 AM
siebenWinkel
siebenWinkel - avatar
0
depends if the var is declared inside or outside of the function.
8th Feb 2017, 5:39 AM
Sam