Ch 9 test two
import tools
A programmer using the interactive interpreter wants to use a function defined in the file tools.py. Write a statement that imports the content of tools.py into the interpreter.
from my_funcs import factorial, squared
The following code uses functions defined in my_funcs.py. Complete the import statement at the top of the program SOLUTION a = 5 print('a! =', factorial(a)) print('a^2 =', squared(a))
import my_funcs
The following code uses functions defined in my_funcs.py. Complete the import statement at the top of the program SOLUTION a = 5 print('a! =', my_funcs.factorial(a)) print('a^2 =', my_funcs.squared(a)
www.python.org
Where can you find more info about what you can import?
To keep from writing the same function over and over again in multiple scripts To maintain scripts
Why use a module?...
dependency
a module being required by another program
import
execute the code contained by the module
"__main__"
executing the script
module
file containing Python code that can be imported and can be used by scripts
__name__
global string variable automatically added to every module that contains the name of the module
if __name__ == "__main__"
if true, then the file is being executed as a script and the branch is taken
built-in
module that comes pre-installed with Python
from my_funcs import factorial
my_funcs.py contains definitions for the factorial() and squared() functions. Write a statement that imports only the function factorial from my_funcs.py
from
specify names to import from a module
script
write Python code in a file, and then pass that file as input to the interpreter