Variable scope

A variable usually gets its value through an assignment statement. If it is a formal parameter in a function definition, it gets its value when the function is called. (There is an implicit assignment, as we have noted above.) Subsequent references to the variable recall the assigned value. The region of code in which a variable's assigned values are accessible is called the variable's “scope”. When a variable is referenced outside of its scope, Python complains that it is undefined.

The scope is defined in terms of code “blocks”. In the example above, the function bodies are code blocks. The entire code is also a code block.

A variable's scope extends only to the end of the smallest code block in which its value is assigned. In the above example, the variable N is assigned at the top of the code, so its value is accessible throughout the entire code from there on. Its scope is said to be “global”. The variable pnew, on the other hand, is defined only inside the main() function. So its scope is limited (“local”) to the main() function block. The variable x is defined in the function f(), so its scope is local to that function. In the f_and_df example above, the variables y and dydx are local to that function.

A consequence of variable scoping rules is that the values assigned to the variables y and dydx in the function f_and_df cannot be accessed with those names in the main() function. That is, if you tried to do

  pnew = p - y/dydx

Python would complain that y and dydx are undefined.