Modules are files containing Python code that can be imported into other programs to use the functions and variables defined in them. Libraries are collections of related modules.
You can import a module using the import
keyword:
import math
print(math.sqrt(16))
This imports the math
module and uses its sqrt()
function to calculate the square root of 16.
You can also create your own modules by saving Python code in a file with the .py
extension. For example, if you have a file called my_module.py
:
# my_module.py
def greet(name):
return f"Hello, {name}!"
You can import and use it in another script:
import my_module
print(my_module.greet("Alice"))
Create a module with a function that multiplies two numbers, then import and use that function in a separate Python file.
Answers: A Python module contains reusable code that you can import into other programs. You import a module using the import
keyword.