__name__
containing the module’s name, such as 'math'
for the math
module or 'random'
for the random
moduleinput
and range
) and types (such as, int
, float
and str
) with objects that define those functions and typesz = 'global z'
def print_variables():
y = 'local y in print_variables'
print(y)
print(z)
print_variables()
[3]
calls print_variables
, Python searches the local, global and built-in namespaces as follows: [3]
is not in a function or method, so the session’s global namespace and the built-in namespace are currently accessibleprint_variables
print_variables
is in scope and Python uses the corresponding object to call print_variables
print_variables
begins executing, Python creates the function’s local namespaceprint_variables
defines the local variable y
, Python adds y
to the function’s local namespacey
is now in scope until the function finishes executing.print_variables
calls the built-in function print
, passing y
as the argumenty
and print
. y
is defined in the local namespace, so it’s in scope and Python will use the corresponding object as print
’s argumentprint
’s corresponding objectprint
print
print
print
is in scope and Python uses the corresponding object to call print
print_variables
calls the built-in function print
again with the argument z
, which is not defined in the local namespacez
is defined in the global namespace, so z
is in scope and Python will use the corresponding object as print
’s argumentprint_variables
function’s suite, so the function terminates and its local namespace no longer exists, meaning the local variable y
is now undefinedy
y
in the session’s global namespacey
is not defined there, so Python searches for y
in the built-in namespacey
NameError
, indicating that y
is not defined.print_variables
and z
still exist in the session’s global namespace, so we can continue using themz
object
NameError
occurs__init__
method starts with an empty object (self
) and adds each attribute to the object’s namespace©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.