Creating & Importing modules
Creating & Importing modules
Creating and importing modules in Python is a fundamental concept that allows you to organize your code into reusable and manageable components. Let's go through the process of creating a module and then importing it into another Python script.
### Creating a Module:
1. Create a Python File:
- Start by creating a new Python file. For example, let's create a file named `mymodule.py`.
2. Define Functions or Variables:
- In `mymodule.py`, define functions, classes, or variables that you want to include in the module:
```python
# mymodule.py
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
```
### Importing a Module:
Now, let's create another Python script and import the `mymodule` module.
1. Create Another Python File:
- Create a new Python file in the same directory as `mymodule.py`. For example, let's create a file named `main.py`.
2. Import the Module:
- In `main.py`, import the `mymodule` module using the `import` keyword:
```python
# main.py
import mymodule
name = "Alice"
message = mymodule.greet(name)
print(message)
print("Value of pi:", mymodule.pi)
```
3. Run the Main Script:
- Run `main.py` using a Python interpreter. It will import `mymodule.py` and use the functions and variables defined within it.
```
$ python main.py
Hello, Alice!
Value of pi: 3.14159
```
In this example, `mymodule.greet(name)` calls the `greet()` function from the `mymodule` module, and `mymodule.pi` accesses the `pi` variable from the module.
Comments
Post a Comment