python - Non-global variable recognized/accepted in defined function -


i learning , experimenting python , accidentally found strange (to me) case. searched as could not find other how use global , local variables or how use 'for' loop. have following code (python 3.2 on android qpython3), modified simplicity:

def get_number():     x=5**i     print(x)     return(x)  in range(1,5):     y=get_number()     print(y) 

i realized made mistake using variable in called function did not define global. , yet, when ran script worked(!) giving me following output:

hon.sh "/storage/emulated/0/com.hipipal.qpyplus/scripts3/ak_scripts/.last_tmp.py" && exit               < 5 5 25 25 125 125 625 625  #[qpython] press enter exit 

could please explain how/why variable recognised within called function , having value has in calling function, though not defined global?

scope resolution variable follows legb rule, i.e. python tries find variable in following scopes (decreasing precedence):

local -> enclosed -> global -> built-in

in case, i defined in enclosed scope.

for further details see http://spartanideas.msu.edu/2014/05/12/a-beginners-guide-to-pythons-namespaces-scope-resolution-and-the-legb-rule/


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo