Learn About Module Importing
In this step, you will learn about module importing in Python. Modules are files containing Python definitions and statements. The import
statement is used to bring modules into your current program, allowing you to use the functions and variables defined within them.
First, let's create a simple module. Open the VS Code editor in the LabEx environment and create a new file named my_module.py
in the ~/project
directory.
## ~/project/my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
This module defines a function greet
and a variable PI
. Now, let's create another Python file to import and use this module. Create a new file named main.py
in the ~/project
directory.
## ~/project/main.py
import my_module
name = "LabEx User"
greeting = my_module.greet(name)
print(greeting)
print("PI =", my_module.PI)
In this main.py
file, we use the import my_module
statement to bring in the my_module
we created earlier. We then access the greet
function and the PI
variable using the dot notation (my_module.greet
, my_module.PI
).
To run this code, open a terminal in the LabEx environment (it should already be open in the bottom panel of VS Code). Make sure your current directory is ~/project
. If not, navigate to it using the cd
command:
cd ~/project
Now, execute the main.py
script using the python
command:
python main.py
You should see the following output:
Hello, LabEx User!
PI = 3.14159
This demonstrates how to import a module and use its contents in another Python file.