Modules & Libraries
What Are Modules?
- Think of a module as a code library, a file that contains a set of functions and variables that you want to include in your application.
Built-in Modules:
- Python has several built-in modules that you can import and use whenever you like.
Example: Importing a Built-in Module:
Import and use the
platformmodule:pythonimport platform x = platform.system() print(x) # Output might be: 'Windows', 'Linux', or 'Darwin' (for Mac)
Using the dir() Function:
- The
dir()function lists all the function names (or variable names) in a module.
Example: Listing Names in a Module:
python
import platform
x = dir(platform)
print(x) # Output: A list of all the defined names in the platform module
Importing Specific Parts from a Module:
- You can choose to import only specific parts of a module using the
fromkeyword.
Example: Importing Specific Parts:
Consider a module named
mymodulewith a function and a dictionary:pythondef greeting(name): print("Hello, " + name) person1 = { "name": "John", "age": 36, "country": "Norway" }Importing only the
person1dictionary frommymodule:pythonfrom mymodule import person1 print(person1["age"]) # Output: 36- Note: When importing using the
fromkeyword, refer to the elements directly, not using the module name (e.g.,person1["age"]instead ofmymodule.person1["age"]).
- Note: When importing using the
Exercises:
- Import and Use a Built-in Module:
Import the
mathmodule and print the square root of 25.pythonimport math print(math.sqrt(25)) # Output: 5.0
- List Names in a Module:
Use the
dir()function to list all names in therandommodule.pythonimport random print(dir(random)) # Output: A list of all defined names in the random module
- Import Specific Parts:
Create your own module with a function and a variable. Import only the variable and use it in your code.
python# mymodule.py def greet(name): print("Hi, " + name) age = 15 # main.py from mymodule import age print(age) # Output: 15
Summary:
- Modules help organize and reuse code in Python. They can be built-in or user-defined. Practice importing and using modules to understand how to leverage these useful libraries in your programs!