Lesson 32 of 4080%
(Progress persistence is disabled until Phase 9)
Python
Intermediate
Modules and Imports
Organize code into multiple files and use built-in libraries.
Modules and Imports
What You’ll Learn
You’ll learn how to use code from other files and utilize Python’s extensive standard library.
What is a Module?
Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.
If you have a file mymodule.py:
# mymodule.py
def greeting(name):
print("Hello, " + name)
You can use it in another file with the import statement:
import mymodule
mymodule.greeting("Jonathan")
Importing Specific Parts
You can choose to import only parts from a module, by using the from keyword.
from mymodule import greeting
greeting("Jonathan") # No need for mymodule. prefix
Built-in Modules
Python comes with a huge standard library.
import math
print(math.pi) # 3.141592653589793
import random
print(random.randint(1, 10)) # Random number between 1 and 10