A Byte of Python

Page 48

Python en:Functions

Using nonlocal statement We have seen how to access variables in the local and global scope above. There is another kind of scope called "nonlocal" scope which is in-between these two types of scopes. Nonlocal scopes are observed when you define functions inside functions. Since everything in Python is just executable code, you can define functions anywhere. Let's take an example: #!/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() Output: $ python func_nonlocal.py x is 2 Changed local x to 5 How It Works: When we are inside func_inner, the 'x' defined in the first line of func_outer is relatively neither in local scope nor in global scope. We declare that we are using this x by nonlocal x and hence we get access to that variable. Try changing the nonlocal x to global x and also by removing the statement itself and observe the difference in behavior in these two cases.

Default Argument Values For some functions, you may want to make some of its parameters as optional and use default values if the user does not want to provide values for such parameters. This is done with the help of default argument values. You can specify default argument values for parameters by following the parameter name in the function definition with the assignment operator (=) followed by the default value. Note that the default argument value should be a constant. More precisely, the default argument value should be immutable - this is explained in detail in later chapters. For now, just remember this. Example:

48


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.