Hello,
I need some help understanding the nonlocal variables and functions. Currently I'm reading "A byte of Python" to ease myself into the language, which so far seems to be fairly straightforward even if the syntax is a little strange coming from C++.
I have copied a small script from the book:
#!/usr/bin/python
# Filename: func_nonlocal.py
def func_outer():
x = 2
print('x is', x)
def func_inner():
nonlocal x
x = 5
func_inner()
print('Changed local x to', x)
func_outer()
If I'm correct the code is read line by line by the interpreter and that When I call func_outer()
it displays the data in the print(..)
by going through the function one line after another. So what is the point of calling the func_inner()
within the func_outer()
since it is already defined inside the said function.
I ran the code after commenting the func_inner()
and it ran fine without a problem.
Also is defining functions within functions advisable as it seems a rather strange concept, and can you call func_inner()
without having to go through func_outer()
first.
Say like
def func_outer():
x = 2
print('x is', x)
def func_inner():
nonlocal x
x = 5
func_inner()
print('Changed local x to', x)
func_inner() #Just call this
Thanks.
PS. What's the Python code tag? When I call \ I don't get the formating or syntax highlighting.[code=python\] I don't get the formating or syntax highlighting.