Loop Control Statements in C
Introduction to HTML
How to use the Github API
The image tag, anchor tag and the button tag
Ordered and Unordered Lists in HTML
The division tag
HTML Forms
Tables in HTML
Introduction to C Programming
Introduction to Python
Varibles and Datatypes in Python
Operators in Python
Typecasting in Python
Input and Output in Python
If Else in Python
Loops in Python
Break, Continue and Pass in Python
Python practice section 1
Lists in Python
Tuple in Python
Modules in Python
Modules in Python are Python files containing functions, classes, etc. that can be used by other
Python programs. Thus, modules provide a reusable piece of code containing related functions and
classes. A module in Python contains code for a single topic such as the random module which is
used to generate random numbers and the math module which is used to perform mathematical operations
like sqrt, sine, cosine, etc. We can also create our own modules in Python. Let's see how we can use
modules in Python.
- Types of modules
- Importing a module
- Using a module
- Creating your own Module
Jump to specific sections
Types of Modules
There are two types of modules in Python -
- Internal Moddules : These modules come pre-downloaded with Python. Hence, we can use them directly using the import keyword. For example - math, random, requests, etc. are internal modules in Python.
-
External Modules: To use these modules, we need to first download them using pip. pip is a python
manager used to install modules in python. For example - opencv, beautifulsoup etc.
To download external modules, you can run the following command on cmd -
pip install ModuleName
Importing a module
To use a module, we need to import( or load) it in our Python Program. This can be done by using the
import keyword.
Syntax -
Syntax -
import ModuleName
For example -
import math
import random
Using a module
import math
# To import a module using a different name is called aliasing.
import random as rm
# If we want to use only a particular class or function of the module we can write -
from datetime import date # imports only the date class from the datetime module
# To access a variable, function, or class of the module, we must write prefix it with ModuleName.
# so that the Python Interpreter knows where to find a particular function or a class.
print(math.sqrt(4))
print(math.ceil(5.7))
print(math.sin(30))
print(rm.random())
print(rm.randint(1,5))
print(date.today())
print(date.weekday(dt.date.today()))
Output
2.0 6 -0.9880316240928618 -0.9880316240928618 0.2779638369529295 4 2023-06-01 3
Creating your own Module
A Python Module is as simple as creating a Python Program. Any Python program can become a module
and then can be imported into other Python Programs for use.
MyModule.py
def hello_message():
print("hello rapid coders !")
HelloProgram.py
import MyModule
# Accessing the hello_message() function from MyModule
print(MyModule.hello_message())
Output
hello rapid coders !