Lecture # 15 - Modules

Lecture # 15 - Modules

Modules in Python.

Modules:

In Python, a module is a file containing Python definitions and statements. The file name is the module name with the suffix .py. Modules allow you to logically organize your Python code into reusable units. They can contain functions, classes, and variables that can be imported and used in other Python files or interactive sessions.

Example 1:

#File: my_module.py
def greeting(name):
    print(f"My name is {name}")

This is a module that has a function named greeting and it has an argument name . The function is not called in this file. Now we will call this function from the main.py file.

#File: main.py
import my_module
user_input = input("Enter Your Name:")
my_module.greeting(user_input)

To call the function from the module we'll have to first import the module into main.py file, so that we can use the contents in our main file. Then the user is asked to enter his name and that is stored in the variable user_input. And at last the function is called.

Files:

Files Content:

Output:

Example 2:

There are multiple built-in modules in python. You can check the module list here. Each of the module contains many functions. We'll be seeing an example of a built-in module named math .

import math
num = int(input("Enter a Number:"))
print(f"Square Root of {num} = {math.sqrt(num)}")

sqrt is a function in module named math that is used to find the square root of a number.

Output: