Skip to content

Built-in and Online Modules

Built-in Modules

Python has a lot of built-in modules that you can use. You can find the list of all the built-in modules in the Python Standard Library. You can use these modules without installing them. You can import them and use them in your code.

Table of Built-in Modules

S.No.Module NameDescription
1mathThis module provides access to the mathematical functions defined by the C standard.
2randomThis module implements pseudo-random number generators for various distributions.
3datetimeThis module supplies classes for manipulating dates and times.
4calendarThis module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar.
5osThis module provides a portable way of using operating system dependent functionality.
6sysThis module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
7jsonThis module implements a subset of the corresponding CPython module, as described below. For more information, refer to the original CPython documentation: json.
8reThis module provides regular expression matching operations similar to those found in Perl.
9timeThis module provides various time-related functions.
10urllibThis module provides a high-level interface for fetching data across the World Wide Web.
11xmlThis package contains four sub-packages: dom, parsers, sax and etree.
12pickleThis module implements binary protocols for serializing and de-serializing a Python object structure.
13sqlite3This module provides a DB-API 2.0 interface for SQLite databases.
14csvThis module implements classes to read and write tabular data in CSV format.
15stringThis module contains common string operations.
16statisticsThis module provides functions for calculating mathematical statistics of numeric (Real-valued) data.
17collectionsThis module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.
18itertoolsThis module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML.
19functoolsThis module provides tools for adapting or extending functions and other callable objects, without completely rewriting them.
20operatorThis module exports a set of efficient functions corresponding to the intrinsic operators of Python.
21pathlibThis module offers classes representing filesystem paths with semantics appropriate for different operating systems.
22argparseThis module makes it easy to write user-friendly command-line interfaces.
23loggingThis module defines functions and classes which implement a flexible event logging system for applications and libraries.
24unittestThis module provides a rich set of tools for constructing and running tests.
25pdbThe module defines an interactive source code debugger for Python programs.
26timeitThis module provides a simple way to time small bits of Python code.
27doctestThis module provides a tool for scanning a module and validating tests embedded in a program’s docstrings.
28typingThis module provides runtime support for type hints.
29sysconfigThis module provides access to Python’s configuration information.
30tracebackThis module provides a standard interface to extract, format and print stack traces of Python programs.
31gcThis module provides an interface to the optional garbage collector.
32inspectThis module provides several useful functions to help get information about live objects.
33warningsThis module defines a standard warning category class.
34pickleThis module implements binary protocols for serializing and de-serializing a Python object structure.
35copyThis module provides generic shallow and deep copy operations.
36pprintThis module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.
37reprlibThis module provides a version of repr() customized for abbreviated displays of large or deeply nested containers.
38enumThis module defines four enumeration classes that can be used to define unique sets of names and values: Enum, IntEnum, Flag, and IntFlag.
39socketThis module provides access to the BSD socket interface.
40threadingThis module constructs higher-level threading interfaces on top of the lower level thread module.
41multiprocessingThis module allows the programmer to fully leverage multiple processors on a given machine.
42asyncioThis module provides infrastructure for writing single-threaded concurrent code using coroutines.
43subprocessThis module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
44venvThis module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories.
45pkgutilThis module provides utilities for the import system.
46platformThis module provides a portable way of using operating system dependent functionality.
47getpassThis module provides a portable way to handle such password prompts securely.
48shutilThis module offers a number of high-level operations on files and collections of files.
49tempfileThis module generates temporary files and directories.
50gzipThis module provides a simple interface to compress and decompress files just like the GNU programs gzip and gunzip would.

Build-in Functions

Python has a lot of built-in functions that you can use. You can find the list of all the built-in functions in the Python Built-in Functions. You can use these functions without importing them. You can use them in your code.

Table of Built-in Functions

S.No.Function NameDescriptionExample
1abs()This function returns the absolute value of a number.abs(-2)abs(-2)
2aiter()This function returns an asynchronous iterator object.aiter([1, 2, 3])aiter([1, 2, 3])
3all()This function returns True if all elements of the iterable are true (or if the iterable is empty).all([True, False, True])all([True, False, True])
4anext()This function retrieves the next item from the asynchronous iterator by calling its anext() method.anext([1, 2, 3])anext([1, 2, 3])
5any()This function returns True if any element of the iterable is true. If the iterable is empty, return False.any([True, False, True])any([True, False, True])
6ascii()This function returns a string containing a printable representation of an object.ascii('a')ascii('a')
7bin()This function converts an integer number to a binary string prefixed with “0b”.bin(2)bin(2)
8bool()This function converts a value to a Boolean.bool(2)bool(2)
9breakpoint()This function enters the debugger at the call site.breakpoint()breakpoint()
10bytearray()This function returns a new array of bytes.bytearray(2)bytearray(2)
11bytes()This function returns a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256.bytes(2)bytes(2)
12callable()This function returns True if the object argument appears callable, False if not.callable(2)callable(2)
13chr()This function returns a string of one character whose ASCII code is the integer i.chr(2)chr(2)
14classmethod()This function returns a class method for function.classmethod(2)classmethod(2)
15compile()This function returns a code object from source.compile(2)compile(2)
16complex()This function returns a complex number with the value real + imag*1j or converts a string or number to a complex number.complex(2)complex(2)
17delattr()This function deletes the named attribute from the given object.delattr(2)delattr(2)
18dict()This function creates a new dictionary.dict(2)dict(2)
19dir()This function returns the list of names in the current local scope.dir(2)dir(2)
20divmod()This function takes two (non complex) numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using integer division.divmod(2)divmod(2)
21enumerate()This function returns an enumerate object.enumerate(2)enumerate(2)
22eval()This function parses the expression argument and evaluates it as a Python expression.eval(2)eval(2)
23exec()This function executes the given source in the context of globals and locals.exec(2)exec(2)
24filter()This function constructs an iterator from those elements of iterable for which function returns true.filter(2)filter(2)
25float()This function returns a floating point number constructed from a number or string x.float(2)float(2)
26format()This function returns value.format(format_spec).format(2)format(2)
27frozenset()This function returns a new frozenset object, optionally with elements taken from iterable.frozenset(2)frozenset(2)
28getattr()This function returns the value of the named attribute of object.getattr(2)getattr(2)
29globals()This function returns a dictionary representing the current global symbol table.globals(2)globals(2)
30hasattr()This function returns True if the object has the named attribute.hasattr(2)hasattr(2)
31hash()This function returns the hash value of the object (if it has one).hash(2)hash(2)
32help()This function invokes the built-in help system.help(dir)help(dir)
33hex()This function converts an integer number to a lowercase hexadecimal string prefixed with “0x”.hex(2)hex(2)
34id()This function returns the “identity” of an object.id(2)id(2)
35input()This function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.input("Enter your name: ")input("Enter your name: ")
36int()This function returns an integer object constructed from a number or string x, or return 0 if no arguments are given.int(2)int(2)
37isinstance()This function returns True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.isinstance(2)isinstance(2)
38issubclass()This function returns True if class is a subclass (direct, indirect or virtual) of classinfo.issubclass(2)issubclass(2)
39iter()This function returns an iterator object.iter(2)iter(2)
40len()This function returns the length (the number of items) of an object.len(2)len(2)
41list()This function returns a list whose items are the same and in the same order as iterable‘s items.list(2)list(2)
42locals()This function updates and returns a dictionary representing the current local symbol table.locals(2)locals(2)
43map()This function returns an iterator that applies function to every item of iterable, yielding the results.map(2)map(2)
44max()This function returns the largest item in an iterable or the largest of two or more arguments.max(2)max(2)
45memoryview()This function returns a “memory view” object created from the given argument.memoryview(2)memoryview(2)
46min()This function returns the smallest item in an iterable or the smallest of two or more arguments.min(2)min(2)
47next()This function retrieves the next item from the iterator by calling its next() method.next(2)next(2)
48object()This function returns a new featureless object.object(2)object(2)
49oct()This function converts an integer number to an octal string prefixed with “0o”.oct(2)oct(2)
50open()This function returns a file object.open("file.txt")open("file.txt")
51ord()This function returns an integer representing the Unicode character.ord(2)ord(2)
52pow()This function returns x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z).pow(2, 3)pow(2, 3)
53print()This function prints the given object to the standard output device.print("Hello World")print("Hello World")
54property()This function returns a property attribute.property(2)property(2)
55range()This function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.range(2)range(2)
56repr()This function returns a string containing a printable representation of an object.repr(2)repr(2)
57reversed()This function returns a reverse iterator.reversed(2)reversed(2)
58round()This function returns the floating point number rounded off to the given ndigits digits after the decimal point.round(2.345)round(2.345)
59set()This function returns a new set object, optionally with elements taken from iterable.set(2)set(2)
60setattr()This function sets the named attribute on the given object to the specified value.setattr(2)setattr(2)
61slice()This function returns a slice object representing the set of indices specified by range(start, stop, step).slice(2)slice(2)
62sorted()This function returns a new sorted list from the items in iterable.sorted([2, 1, 3])sorted([2, 1, 3])
63staticmethod()This function returns a static method for function.@staticmethod@staticmethod
64str()This function returns a string version of object.str(2)str(2)
65sum()This function returns the sum of all items in an iterable.sum([1, 2, 3])sum([1, 2, 3])
66super()This function returns a proxy object that delegates method calls to a parent or sibling class of type.super(2)super(2)
67tuple()This function returns a tuple whose items are the same and in the same order as iterable‘s items.tuple(2)tuple(2)
68type()This function returns the type of an object.type(2)type(2)
69vars()This function returns the dict attribute for a module, class, instance, or any other object with a dict attribute.vars(2)vars(2)
70zip()This function returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.zip(2)zip(2)
71import()This function is called by the import statement.__import__(2)__import__(2)

Online Modules

There are a lot of modules that are not built-in. You can install them using the Python Package Index (PyPI). You can install them using the pippip command. You can find the list of all the modules on the Python Package Index.

Installing Modules

You can install modules using the pippip command. You can install them using the following command:

command
pip install <module-name>
command
pip install <module-name>

You can also install a specific version of a module using the following command:

command
pip install <module-name>==<version>
command
pip install <module-name>==<version>

You can also install a module using a requirements file. You can create a requirements file using the following command:

command
pip freeze > requirements.txt
command
pip freeze > requirements.txt

You can install all the modules in the requirements file using the following command:

command
pip install -r requirements.txt
command
pip install -r requirements.txt

Table of Online Modules

These are some of the most popular modules that you can install using the pippip command.

S.No.Module NameDescription
1numpyNumPy is the fundamental package for array computing with Python.
2pandaspandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language.
3matplotlibMatplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
4scipySciPy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.
5scikit-learnscikit-learn is a Python module for machine learning built on top of SciPy and distributed under the 3-Clause BSD license.
6tensorflowTensorFlow is an end-to-end open source platform for machine learning.
7kerasKeras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano.
8pytorchPyTorch is an open source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing.
9opencv-pythonOpenCV-Python is a library of Python bindings designed to solve computer vision problems.
10pillowPillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors.
11requestsRequests is an elegant and simple HTTP library for Python, built for human beings.
12beautifulsoup4Beautiful Soup is a library that makes it easy to scrape information from web pages.
13seleniumSelenium is a portable framework for testing web applications.
14flaskFlask is a lightweight WSGI web application framework.
15djangoDjango is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.
16pyqt5PyQt5 is a comprehensive set of Python bindings for Qt v5.
17pyinstallerPyInstaller bundles a Python application and all its dependencies into a single package.
18cx-freezecx_Freeze is a set of scripts and modules for freezing Python scripts into executables in much the same way that py2exe and py2app do.
19py2exepy2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
20py2apppy2app is a Python setuptools command which will allow you to make standalone application bundles and plugins from Python scripts.
21tinydbTinyDB is a lightweight document oriented database optimized for your happiness.
22thinkerThinker is a Python library for building interactive command line interfaces.
23pytubepytube is a lightweight, Pythonic, dependency-free, library (and command-line utility) for downloading YouTube Videos.
24pyautoguiPyAutoGUI lets your Python scripts control the mouse and keyboard to automate interactions with other applications.
25MySQL ConnectorMySQL Connector/Python is a standardized database driver for Python platforms and development.
26psycopg2psycopg2 is a PostgreSQL database adapter for the Python programming language.
27PyGreSQLPyGreSQL is a Python module that interfaces to a PostgreSQL database.
28psycopg2psycopg2 is a PostgreSQL database adapter for the Python programming language.
29cx_Oraclecx_Oracle is a Python extension module that enables access to Oracle Database.
30pymssqlpymssql is the Python language extension module that provides access to Microsoft SQL Servers from Python scripts.
31SQLAlchemySQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
32PyMongoPyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python.
33redisThe Python interface to the Redis key-value store.
34pymemcacheA comprehensive, fast, pure Python memcached client.
35pyscreenshotpyscreenshot is a Python module used to take screenshots.
36pytesseractA Python wrapper for Google Tesseract.
37pywin32pywin32 is a Python extension for Windows.
38virtualenvvirtualenv is a tool to create isolated Python environments.
39pylintPylint is a tool that checks for errors in Python code, tries to enforce a coding standard and looks for code smells.
40autopep8autopep8 automatically formats Python code to conform to the PEP 8 style guide.
41pygamePygame is a set of Python modules designed for writing video games.
42pygletpyglet is a cross-platform windowing and multimedia library for Python.
43vidstreamA cross-platform python package that contains modules for streaming video from your computer to the internet for remote viewing.
44pyexcelA wrapper library to read, manipulate and write data in different excel formats: csv, ods, xls, xlsx and xlsm.
45pipenvPipenv is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world.
46NLTKNLTK is a leading platform for building Python programs to work with human language data.
47pyttsx3pyttsx3 is a text-to-speech conversion library in Python.
48theanoTheano is a Python library that allows you to define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays efficiently.
49dashDash is a Python framework for building analytical web applications.
50streamlitStreamlit is an open-source Python library that makes it easy to build beautiful custom web-apps for machine learning and data science.

Using Modules

You can use the built-in modules in your code. You can import them using the importimport keyword. You can import them using the following syntax:

syntax
import <module-name>
syntax
import <module-name>

You can also import a module using an alias. You can import them using the following syntax:

syntax
import <module-name> as <alias>
syntax
import <module-name> as <alias>

You can also import a specific function from a module. You can import them using the following syntax:

syntax
from <module-name> import <function-name>
syntax
from <module-name> import <function-name>

You can also import all the functions from a module. You can import them using the following syntax:

syntax
from <module-name> import *
syntax
from <module-name> import *

You can also import a specific function from a module using an alias. You can import them using the following syntax:

syntax
from <module-name> import <function-name> as <alias>
syntax
from <module-name> import <function-name> as <alias>

You can also import all the functions from a module using an alias. You can import them using the following syntax:

syntax
from <module-name> import * as <alias>
syntax
from <module-name> import * as <alias>

Example

You can use the mathmath module in your code. You can import it using the following syntax:

math.py
import math
 
print(math.pi)
math.py
import math
 
print(math.pi)

Output:

command
C:\Users\username>python math.py
3.141592653589793
command
C:\Users\username>python math.py
3.141592653589793

You can also import a specific function from a module. You can import it using the following syntax:

math.py
from math import pi
print(pi)
math.py
from math import pi
print(pi)

Output:

command
C:\Users\username>python math.py
3.141592653589793
command
C:\Users\username>python math.py
3.141592653589793

You can also import a specific function from a module using an alias. You can import it using the following syntax:

math.py
from math import pi as PI
 
print(PI)
math.py
from math import pi as PI
 
print(PI)

Output:

command
C:\Users\username>python math.py
3.141592653589793
command
C:\Users\username>python math.py
3.141592653589793

You can also import all the functions from a module. You can import it using the following syntax:

math.py
from math import *
 
print(pi)
math.py
from math import *
 
print(pi)

Output:

command
C:\Users\username>python math.py
3.141592653589793
command
C:\Users\username>python math.py
3.141592653589793

Some Useful Modules

Math Module

Math module is used to perform mathematical operations. It provides access to the mathematical functions defined by the C standard. It is always available in Python. It provides various mathematical operations like trigonometric operations, exponential operations, logarithmic operations, etc. It also provides some constants like pi, e, etc. It is used by importing the math module in the program. It is used in the following way:

math.py
import math
 
print(math.pi)
print(math.pow(2, 3))
math.py
import math
 
print(math.pi)
print(math.pow(2, 3))

Output:

command
C:\Users\username>python math.py
3.141592653589793
8.0
command
C:\Users\username>python math.py
3.141592653589793
8.0

In this example, we have used the pipi constant to print the value of pi. We have also used the pow()pow() function to calculate the power of a number.

Some Important Functions of Math Module

S.No.Function NameDescriptionExample
1ceil(x)Returns the smallest integer greater than or equal to x.math.ceil(2.3)math.ceil(2.3)
2copysign(x, y)Returns x with the sign of y.math.copysign(2, -3)math.copysign(2, -3)
3fabs(x)Returns the absolute value of x.math.fabs(-2.3)math.fabs(-2.3)
4factorial(x)Returns the factorial of x.math.factorial(4)math.factorial(4)
5floor(x)Returns the largest integer less than or equal to x.math.floor(2.3)math.floor(2.3)
6fmod(x, y)Returns the remainder when x is divided by y.math.fmod(2, 3)math.fmod(2, 3)
7frexp(x)Returns the mantissa and exponent of x as the pair (m, e).math.frexp(2)math.frexp(2)
8fsum(iterable)Returns an accurate floating point sum of values in the iterable.math.fsum([1, 2, 3, 4, 5])math.fsum([1, 2, 3, 4, 5])
9isfinite(x)Returns True if x is neither an infinity nor a NaN (Not a Number).math.isfinite(2)math.isfinite(2)
10isinf(x)Returns True if x is a positive or negative infinity.math.isinf(2)math.isinf(2)
11isnan(x)Returns True if x is a NaN.math.isnan(2)math.isnan(2)
12ldexp(x, i)Returns x * (2**i).math.ldexp(2, 3)math.ldexp(2, 3)
13modf(x)Returns the fractional and integer parts of x.math.modf(2.3)math.modf(2.3)
14trunc(x)Returns the truncated integer value of x.math.trunc(2.3)math.trunc(2.3)
15exp(x)Returns e**x.math.exp(2)math.exp(2)
16expm1(x)Returns e**x - 1.math.expm1(2)math.expm1(2)
17log(x[, base])Returns the logarithm of x to the base (defaults to e).math.log(2)math.log(2)
18log1p(x)Returns the natural logarithm of 1+x.math.log1p(2)math.log1p(2)
19log2(x)Returns the base-2 logarithm of x.math.log2(2)math.log2(2)
20log10(x)Returns the base-10 logarithm of x.math.log10(2)math.log10(2)
21pow(x, y)Returns x raised to the power y.math.pow(2, 3)math.pow(2, 3)
22sqrt(x)Returns the square root of x.math.sqrt(2)math.sqrt(2)
23acos(x)Returns the arc cosine of x.math.acos(2)math.acos(2)
24asin(x)Returns the arc sine of x.math.asin(2)math.asin(2)
25atan(x)Returns the arc tangent of x.math.atan(2)math.atan(2)
26atan2(y, x)Returns atan(y / x).math.atan2(2, 3)math.atan2(2, 3)
27cos(x)Returns the cosine of x.math.cos(2)math.cos(2)
28hypot(x, y)Returns the Euclidean norm, sqrt(xx + yy).math.hypot(2, 3)math.hypot(2, 3)
29sin(x)Returns the sine of x.math.sin(2)math.sin(2)
30tan(x)Returns the tangent of x.math.tan(2)math.tan(2)
31degrees(x)Converts angle x from radians to degrees.math.degrees(2)math.degrees(2)
32radians(x)Converts angle x from degrees to radians.math.radians(2)math.radians(2)
33acosh(x)Returns the inverse hyperbolic cosine of x.math.acosh(2)math.acosh(2)
34asinh(x)Returns the inverse hyperbolic sine of x.math.asinh(2)math.asinh(2)
35atanh(x)Returns the inverse hyperbolic tangent of x.math.atanh(2)math.atanh(2)
36cosh(x)Returns the hyperbolic cosine of x.math.cosh(2)math.cosh(2)
37sinh(x)Returns the hyperbolic cosine of x.math.sinh(2)math.sinh(2)
38tanh(x)Returns the hyperbolic tangent of x.math.tanh(2)math.tanh(2)
39erf(x)Returns the error function at x.math.erf(2)math.erf(2)
40erfc(x)Returns the complementary error function at x.math.erfc(2)math.erfc(2)
41gamma(x)Returns the Gamma function at x.math.gamma(2)math.gamma(2)
42lgamma(x)Returns the natural logarithm of the absolute value of the Gamma function at x.math.lgamma(2)math.lgamma(2)
43piMathematical constant, the ratio of circumference of a circle to it’s diameter (3.14159…)math.pimath.pi
44emathematical constant e (2.71828…)math.emath.e
45taumathematical constant tau (6.28318…)math.taumath.tau
46inffloating-point positive infinitymath.infmath.inf
47nanfloating-point NaN (not a number)math.nanmath.nan
48isqrt(n)Returns the integer square root of the nonnegative integer n.math.isqrt(2)math.isqrt(2)
49comb(n, k)Returns the number of ways to choose k items from n items without repetition and without order.math.comb(2, 3)math.comb(2, 3)
50perm(n, k)Returns the number of ways to choose k items from n items without repetition and with order.math.perm(2, 3)math.perm(2, 3)

Random Module

Random module is used to perform random operations. It provides access to the pseudo-random number generators for various distributions. It is always available in Python. It provides various random operations like generating random numbers, shuffling a list, etc. It is used by importing the random module in the program. It is used in the following way:

random.py
import random
 
print(random.random())
print(random.randint(1, 10))
random.py
import random
 
print(random.random())
print(random.randint(1, 10))

Output:

command
C:\Users\username>python random.py
0.940667756167586
7
command
C:\Users\username>python random.py
0.940667756167586
7

In this example, we have used the random()random() function to generate a random number between 0 and 1. We have also used the randint()randint() function to generate a random integer between 1 and 10.

Some Important Functions of Random Module

S.No.Function NameDescriptionExample
1random()Returns a random float number between 0 and 1.random.random()random.random()
2randint(a, b)Returns a random integer between a and b.random.randint(1, 10)random.randint(1, 10)
3randrange(start, stop[, step])Returns a randomly selected element from range(start, stop, step).random.randrange(1, 10, 2)random.randrange(1, 10, 2)
4choice(seq)Returns a random element from the non-empty sequence seq.random.choice([1, 2, 3, 4, 5])random.choice([1, 2, 3, 4, 5])
5choices(population[, weights=None, *, cum_weights=None, k=1])Returns a k sized list of elements chosen from the population with replacement.random.choices([1, 2, 3, 4, 5], k=3)random.choices([1, 2, 3, 4, 5], k=3)
6shuffle(x[, random])Shuffle the sequence x in place.random.shuffle([1, 2, 3, 4, 5])random.shuffle([1, 2, 3, 4, 5])
7sample(population, k)Returns a k length list of unique elements chosen from the population sequence or set.random.sample([1, 2, 3, 4, 5], k=3)random.sample([1, 2, 3, 4, 5], k=3)
8seed([x])Initialize the random number generator.random.seed(10)random.seed(10)
9getstate()Return an object capturing the current internal state of the generator.random.getstate()random.getstate()
10setstate(state)Restore the internal state of the generator.random.setstate(state)random.setstate(state)
11getrandbits(k)Returns a non-negative Python integer with k random bits.random.getrandbits(5)random.getrandbits(5)
12uniform(a, b)Returns a random floating point number between a and b.random.uniform(1, 10)random.uniform(1, 10)
13triangular(low, high, mode)Returns a random floating point number between low and high, with the specified mode between those bounds.random.triangular(1, 10, 5)random.triangular(1, 10, 5)
14betavariate(alpha, beta)Beta distribution.random.betavariate(1, 10)random.betavariate(1, 10)
15expovariate(lambd)Exponential distribution.random.expovariate(1)random.expovariate(1)
16gammavariate(alpha, beta)Gamma distribution.random.gammavariate(1, 10)random.gammavariate(1, 10)
17gauss(mu, sigma)Gaussian distribution.random.gauss(1, 10)random.gauss(1, 10)
18lognormvariate(mu, sigma)Log normal distribution.random.lognormvariate(1, 10)random.lognormvariate(1, 10)
19normalvariate(mu, sigma)Normal distribution.random.normalvariate(1, 10)random.normalvariate(1, 10)
20vonmisesvariate(mu, kappa)von Mises distribution.random.vonmisesvariate(1, 10)random.vonmisesvariate(1, 10)
21paretovariate(alpha)Pareto distribution.random.paretovariate(1)random.paretovariate(1)
22weibullvariate(alpha, beta)Weibull distribution.random.weibullvariate(1, 10)random.weibullvariate(1, 10)

Datetime Module

Datetime module is used to perform date and time operations. It provides access to the date and time functions. It is always available in Python. It provides various date and time operations like getting the current date and time, getting the current year, getting the current month, etc. It is used by importing the datetime module in the program. It is used in the following way:

datetime.py
import datetime
 
print(datetime.datetime.now())
print(datetime.date(2021,12,11).strftime("%A"))
datetime.py
import datetime
 
print(datetime.datetime.now())
print(datetime.date(2021,12,11).strftime("%A"))

Output:

command
C:\Users\username>python datetime.py
2023-12-01 12:00:00.000000
Saturday
command
C:\Users\username>python datetime.py
2023-12-01 12:00:00.000000
Saturday

In this example, we have used the now()now() function to get the current date and time. We have also used the strftime()strftime() function to get the day of the week from a date.

Some Important Functions of Datetime Module

S.No.Function NameDescriptionExample
1date(year, month, day)Returns a date object with the specified year, month, and day.datetime.date(2021, 12, 11)datetime.date(2021, 12, 11)
2datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])Returns a datetime object with the specified year, month, day, hour, minute, second, microsecond, and tzinfo.datetime.datetime(2021, 12, 11, 12, 0, 0, 0)datetime.datetime(2021, 12, 11, 12, 0, 0, 0)
3time([hour[, minute[, second[, microsecond[, tzinfo]]]]])Returns a time object with the specified hour, minute, second, microsecond, and tzinfo.datetime.time(12, 0, 0, 0)datetime.time(12, 0, 0, 0)
4timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])Returns a timedelta object with the specified days, seconds, microseconds, milliseconds, minutes, hours, and weeks.datetime.timedelta(1)datetime.timedelta(1)
5today()Returns the current local date.datetime.datetime.today()datetime.datetime.today()
6now([tz])Returns the current local date and time.datetime.datetime.now()datetime.datetime.now()
7utcnow()Returns the current UTC date and time.datetime.datetime.utcnow()datetime.datetime.utcnow()
8fromtimestamp(timestamp[, tz])Returns the local date and time corresponding to the POSIX timestamp.datetime.datetime.fromtimestamp(1639209000)datetime.datetime.fromtimestamp(1639209000)
9utcfromtimestamp(timestamp)Returns the UTC date and time corresponding to the POSIX timestamp.datetime.datetime.utcfromtimestamp(1639209000)datetime.datetime.utcfromtimestamp(1639209000)
10combine(date, time)Returns a datetime object with the specified date and time.datetime.datetime.combine(datetime.date(2021, 12, 11), datetime.time(12, 0, 0, 0))datetime.datetime.combine(datetime.date(2021, 12, 11), datetime.time(12, 0, 0, 0))
11strptime(date_string, format)Returns a datetime corresponding to date_string, parsed according to format.datetime.datetime.strptime("2021-12-11", "%Y-%m-%d")datetime.datetime.strptime("2021-12-11", "%Y-%m-%d")
12strftime(format)Returns a string representing the date and time, controlled by an explicit format string.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).strftime("%A")datetime.datetime(2021, 12, 11, 12, 0, 0, 0).strftime("%A")
13date()Returns the date part.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).date()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).date()
14time()Returns the time part.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).time()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).time()
15replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).replace(2021, 12, 11)datetime.datetime(2021, 12, 11, 12, 0, 0, 0).replace(2021, 12, 11)
16astimezone(tz=None)Returns a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).astimezone()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).astimezone()
17timetuple()Returns a time.struct_time such as returned by time.localtime().datetime.datetime(2021, 12, 11, 12, 0, 0, 0).timetuple()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).timetuple()
18utctimetuple()Returns a time.struct_time such as returned by time.gmtime().datetime.datetime(2021, 12, 11, 12, 0, 0, 0).utctimetuple()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).utctimetuple()
19toordinal()Returns the proleptic Gregorian ordinal of the date.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).toordinal()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).toordinal()
20timestamp()Returns POSIX timestamp corresponding to the datetime instance.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).timestamp()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).timestamp()
21ctime()Returns a string representing the date and time.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).ctime()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).ctime()
22isoformat([sep=‘T’, timespec=‘auto’])Returns a string representing the date and time in ISO 8601 format.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).isoformat()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).isoformat()
23str()Returns a string representing the date and time.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).__str__()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).__str__()
24repr()Returns a string representing the date and time.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).__repr__()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).__repr__()
25weekday()Returns the day of the week as an integer, where Monday is 0 and Sunday is 6.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).weekday()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).weekday()
26isoweekday()Returns the day of the week as an integer, where Monday is 1 and Sunday is 7.datetime.datetime(2021, 12, 11, 12, 0, 0, 0).isoweekday()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).isoweekday()
27isocalendar()Returns a 3-tuple, (ISO year, ISO week number, ISO weekday).datetime.datetime(2021, 12, 11, 12, 0, 0, 0).isocalendar()datetime.datetime(2021, 12, 11, 12, 0, 0, 0).isocalendar()
28fromisocalendar(year, week, day)Returns the date corresponding to the specified ISO year, week number, and weekday.datetime.datetime.fromisocalendar(2021, 12, 11)datetime.datetime.fromisocalendar(2021, 12, 11)

OS Module

OS module is used to perform operating system operations. It provides access to the operating system functions. It is always available in Python. It provides various operating system operations like getting the current working directory, changing the current working directory, etc. It is used by importing the os module in the program. It is used in the following way:

os.py
import os
 
print(os.getcwd())
os.chdir("C:\\Users\\username\\Desktop")
print(os.getcwd())
os.py
import os
 
print(os.getcwd())
os.chdir("C:\\Users\\username\\Desktop")
print(os.getcwd())

Output:

command
C:\Users\username>python os.py
C:\Users\username
C:\Users\username\Desktop
command
C:\Users\username>python os.py
C:\Users\username
C:\Users\username\Desktop

In this example, we have used the getcwd()getcwd() function to get the current working directory. We have also used the chdir()chdir() function to change the current working directory.

Some Important Functions of OS Module

S.No.Function NameDescriptionExample
1chdir(path)Changes the current working directory to path.os.chdir("C:\\Users\\username\\Desktop")os.chdir("C:\\Users\\username\\Desktop")
2getcwd()Returns the current working directory.os.getcwd()os.getcwd()
3listdir(path=’.‘)Returns a list containing the names of the entries in the directory given by path.os.listdir("C:\\Users\\username\\Desktop")os.listdir("C:\\Users\\username\\Desktop")
4mkdir(path, mode=0o777, *, dir_fd=None)Creates a directory named path with numeric mode mode.os.mkdir("C:\\Users\\username\\Desktop\\New Folder")os.mkdir("C:\\Users\\username\\Desktop\\New Folder")
5makedirs(name, mode=0o777, exist_ok=False)Recursive directory creation function.os.makedirs("C:\\Users\\username\\Desktop\\New Folder\\New Folder")os.makedirs("C:\\Users\\username\\Desktop\\New Folder\\New Folder")
6rmdir(path, *, dir_fd=None)Removes the directory path.os.rmdir("C:\\Users\\username\\Desktop\\New Folder\\New Folder")os.rmdir("C:\\Users\\username\\Desktop\\New Folder\\New Folder")
7removedirs(name)Removes directories recursively.os.removedirs("C:\\Users\\username\\Desktop\\New Folder\\New Folder")os.removedirs("C:\\Users\\username\\Desktop\\New Folder\\New Folder")
8rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)Renames the file or directory src to dst.os.rename("C:\\Users\\username\\Desktop\\New Folder", "C:\\Users\\username\\Desktop\\New Folder 1")os.rename("C:\\Users\\username\\Desktop\\New Folder", "C:\\Users\\username\\Desktop\\New Folder 1")
9renames(old, new)Renames the file or directory old to new, recursively.os.renames("C:\\Users\\username\\Desktop\\New Folder", "C:\\Users\\username\\Desktop\\New Folder 1")os.renames("C:\\Users\\username\\Desktop\\New Folder", "C:\\Users\\username\\Desktop\\New Folder 1")
10remove(path, *, dir_fd=None)Removes (deletes) the file path.os.remove("C:\\Users\\username\\Desktop\\New Folder")os.remove("C:\\Users\\username\\Desktop\\New Folder")
11rmtree(path, ignore_errors=False, onerror=None)Deletes an entire directory tree.os.rmtree("C:\\Users\\username\\Desktop\\New Folder")os.rmtree("C:\\Users\\username\\Desktop\\New Folder")
12system(command)Executes the command (a string) in a subshell.os.system("dir")os.system("dir")
13walk(top, topdown=True, onerror=None, followlinks=False)Generates the file names in a directory tree by walking the tree either top-down or bottom-up.os.walk("C:\\Users\\username\\Desktop")os.walk("C:\\Users\\username\\Desktop")
14path.abspath(path)Returns the absolute path of path.os.path.abspath("C:\\Users\\username\\Desktop")os.path.abspath("C:\\Users\\username\\Desktop")
15path.basename(path)Returns the base name of path.os.path.basename("C:\\Users\\username\\Desktop")os.path.basename("C:\\Users\\username\\Desktop")
16path.commonpath(paths)Returns the longest common sub-path of each pathname in paths.os.path.commonpath(["C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop\\New Folder"])os.path.commonpath(["C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop\\New Folder"])
17path.commonprefix(list)Returns the longest path prefix (taken character-by-character) that is a prefix of all paths in list.os.path.commonprefix(["C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop\\New Folder"])os.path.commonprefix(["C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop\\New Folder"])
18path.dirname(path)Returns the directory name of path.os.path.dirname("C:\\Users\\username\\Desktop")os.path.dirname("C:\\Users\\username\\Desktop")
19path.exists(path)Returns True if path refers to an existing path.os.path.exists("C:\\Users\\username\\Desktop")os.path.exists("C:\\Users\\username\\Desktop")
20path.lexists(path)Returns True if path refers to an existing path.os.path.lexists("C:\\Users\\username\\Desktop")os.path.lexists("C:\\Users\\username\\Desktop")
21path.expanduser(path)Expands ~ and ~user constructions.os.path.expanduser("~")os.path.expanduser("~")
22path.expandvars(path)Expands shell variables.os.path.expandvars("%USERPROFILE%")os.path.expandvars("%USERPROFILE%")
23path.getatime(path)Returns the time of last access of path.os.path.getatime("C:\\Users\\username\\Desktop")os.path.getatime("C:\\Users\\username\\Desktop")
24path.getmtime(path)Returns the time of last modification of path.os.path.getmtime("C:\\Users\\username\\Desktop")os.path.getmtime("C:\\Users\\username\\Desktop")
25path.getctime(path)Returns the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path.os.path.getctime("C:\\Users\\username\\Desktop")os.path.getctime("C:\\Users\\username\\Desktop")
26path.getsize(path)Returns the size, in bytes, of path.os.path.getsize("C:\\Users\\username\\Desktop")os.path.getsize("C:\\Users\\username\\Desktop")
27path.isabs(path)Returns True if path is an absolute pathname.os.path.isabs("C:\\Users\\username\\Desktop")os.path.isabs("C:\\Users\\username\\Desktop")
28path.isfile(path)Returns True if path is an existing regular file.os.path.isfile("C:\\Users\\username\\Desktop")os.path.isfile("C:\\Users\\username\\Desktop")
29path.isdir(path)Returns True if path is an existing directory.os.path.isdir("C:\\Users\\username\\Desktop")os.path.isdir("C:\\Users\\username\\Desktop")
30path.islink(path)Returns True if path refers to a directory entry that is a symbolic link.os.path.islink("C:\\Users\\username\\Desktop")os.path.islink("C:\\Users\\username\\Desktop")
31path.ismount(path)Returns True if pathname path is a mount point: a point in a file system where a different file system has been mounted.os.path.ismount("C:\\Users\\username\\Desktop")os.path.ismount("C:\\Users\\username\\Desktop")
32path.join(path1[, path2[, …]])Joins one or more path components intelligently.os.path.join("C:\\Users\\username\\Desktop", "New Folder")os.path.join("C:\\Users\\username\\Desktop", "New Folder")
33path.normcase(path)Normalizes the case of a pathname.os.path.normcase("C:\\Users\\username\\Desktop")os.path.normcase("C:\\Users\\username\\Desktop")
34path.normpath(path)Normalizes path, eliminating double slashes, etc.os.path.normpath("C:\\Users\\username\\Desktop")os.path.normpath("C:\\Users\\username\\Desktop")
35path.realpath(path)Returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path.os.path.realpath("C:\\Users\\username\\Desktop")os.path.realpath("C:\\Users\\username\\Desktop")
36path.relpath(path[, start])Returns a relative filepath to path either from the current directory or from an optional start directory.os.path.relpath("C:\\Users\\username\\Desktop")os.path.relpath("C:\\Users\\username\\Desktop")
37path.samefile(path1, path2)Returns True if both pathname arguments refer to the same file or directory.os.path.samefile("C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop")os.path.samefile("C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop")
38path.sameopenfile(fp1, fp2)Returns True if the file descriptors fp1 and fp2 refer to the same file.os.path.sameopenfile("C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop")os.path.sameopenfile("C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop")
39path.samestat(stat1, stat2)Returns True if the stat tuples stat1 and stat2 refer to the same file.os.path.samestat("C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop")os.path.samestat("C:\\Users\\username\\Desktop", "C:\\Users\\username\\Desktop")
40path.split(path)Splits the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that.os.path.split("C:\\Users\\username\\Desktop")os.path.split("C:\\Users\\username\\Desktop")

Sys Module

Sys module is used to perform system operations. It provides access to the variables and functions related to the Python interpreter. It is always available in Python. It provides various system operations like getting the command line arguments, getting the Python version, etc. It is used by importing the sys module in the program. It is used in the following way:

sys.py
import sys
 
print(sys.argv)
print(sys.version)
sys.py
import sys
 
print(sys.argv)
print(sys.version)

Output:

command
C:\Users\username>python sys.py 1 2 3
['sys.py', '1', '2', '3']
3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:04:37) [MSC v.1929 64 bit (AMD64)]
command
C:\Users\username>python sys.py 1 2 3
['sys.py', '1', '2', '3']
3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:04:37) [MSC v.1929 64 bit (AMD64)]

In this example, we have used the argvargv variable to get the command line arguments. We have also used the versionversion variable to get the Python version.

Some Important Functions of Sys Module

S.No.Function NameDescriptionExample
1argvContains the command line arguments passed to the Python program.sys.argvsys.argv
2versionContains the Python version.sys.versionsys.version
3version_infoContains the Python version information.sys.version_infosys.version_info
4hexversionContains the Python version information in hexadecimal.sys.hexversionsys.hexversion
5maxsizeContains the maximum size of an integer.sys.maxsizesys.maxsize
6pathContains the search path for modules.sys.pathsys.path
7platformContains the platform identifier.sys.platformsys.platform
8stdinContains the standard input stream.sys.stdinsys.stdin
9stdoutContains the standard output stream.sys.stdoutsys.stdout
10stderrContains the standard error stream.sys.stderrsys.stderr
11exit([status])Exits from Python.sys.exit()sys.exit()
12getrefcount(object)Returns the reference count of the object.sys.getrefcount(1)sys.getrefcount(1)
13getsizeof(object[, default])Returns the size of the object.sys.getsizeof(1)sys.getsizeof(1)
14gettrace()Returns the global debug tracing function.sys.gettrace()sys.gettrace()

Time Module

Time module is used to perform time operations. It provides access to the time functions. It is always available in Python. It provides various time operations like getting the current time, getting the current year, getting the current month, etc. It is used by importing the time module in the program. It is used in the following way:

time.py
import time
 
print(time.time())
print(time.localtime())
time.py
import time
 
print(time.time())
print(time.localtime())

Output:

command
C:\Users\username>python time.py
1639209000.0
time.struct_time(tm_year=2021, tm_mon=12, tm_mday=11, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=345, tm_isdst=0)
command
C:\Users\username>python time.py
1639209000.0
time.struct_time(tm_year=2021, tm_mon=12, tm_mday=11, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=345, tm_isdst=0)

In this example, we have used the time()time() function to get the current time. We have also used the localtime()localtime() function to get the current time in the local timezone.

Some Important Functions of Time Module

S.No.Function NameDescriptionExample
1time()Returns the time in seconds since the epoch as a floating point number.time.time()time.time()
2ctime([secs])Converts a time expressed in seconds since the epoch to a string representing local time.time.ctime(1639209000)time.ctime(1639209000)
3gmtime([secs])Converts a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero.time.gmtime(1639209000)time.gmtime(1639209000)
4localtime([secs])Converts a time expressed in seconds since the epoch to a struct_time in local time.time.localtime(1639209000)time.localtime(1639209000)
5mktime(t)Accepts an instant expressed as a time tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.time.mktime(time.localtime(1639209000))time.mktime(time.localtime(1639209000))
6sleep(secs)Suspends the calling thread for secs seconds.time.sleep(1)time.sleep(1)
7strftime(format[, t])Converts a struct_time or full 9-tuple time tuple to a string according to a format specification.time.strftime("%A", time.localtime(1639209000))time.strftime("%A", time.localtime(1639209000))
8strptime(string[, format])Parses a string representing a time according to a format.time.strptime("2021-12-11", "%Y-%m-%d")time.strptime("2021-12-11", "%Y-%m-%d")
9time_ns()Returns the time in nanoseconds since the epoch.time.time_ns()time.time_ns()
10timezoneThe offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).time.timezonetime.timezone
11tznameA tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone.time.tznametime.tzname
12altzoneThe offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK).time.altzonetime.altzone
13daylightNonzero if a DST timezone is defined.time.daylighttime.daylight
14struct_timeThe type of the time value sequence returned by gmtime(), localtime(), and strptime().time.struct_timetime.struct_time

Calendar Module

Calendar module is used to perform calendar operations. It provides access to the calendar functions. It is always available in Python. It provides various calendar operations like getting the calendar of a month, getting the calendar of a year, etc. It is used by importing the calendar module in the program. It is used in the following way:

calendar.py
import calendar
 
print(calendar.month(2021, 12))
print(calendar.calendar(2021))
calendar.py
import calendar
 
print(calendar.month(2021, 12))
print(calendar.calendar(2021))

Output:

command
C:\Users\username>python calendar.py
   December 2021
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
 
                                  2021
 
      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
             1  2  3       1  2  3  4  5  6  7       1  2  3  4  5  6  7
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       8  9 10 11 12 13 14
11 12 13 14 15 16 17      15 16 17 18 19 20 21      15 16 17 18 19 20 21
18 19 20 21 22 23 24      22 23 24 25 26 27 28      22 23 24 25 26 27 28
25 26 27 28 29 30 31                                29 30 31
 
       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                      1  2          1  2  3  4  5  6
 5  6  7  8  9 10 11       3  4  5  6  7  8  9       7  8  9 10 11 12 13
12 13 14 15 16 17 18      10 11 12 13 14 15 16      14 15 16 17 18 19 20
19 20 21 22 23 24 25      17 18 19 20 21 22 23      21 22 23 24 25 26 27
26 27 28 29 30            24 25 26 27 28 29 30      28 29 30
                          31
 
        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                         1             1  2  3  4  5
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       6  7  8  9 10 11 12
12 13 14 15 16 17 18       9 10 11 12 13 14 15      13 14 15 16 17 18 19
19 20 21 22 23 24 25      16 17 18 19 20 21 22      20 21 22 23 24 25 26
26 27 28 29 30 31         23 24 25 26 27 28 29      27 28 29 30
                          30 31
 
      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
             1  2  3       1  2  3  4  5  6  7             1  2  3  4  5
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       6  7  8  9 10 11 12
11 12 13 14 15 16 17      15 16 17 18 19 20 21      13 14 15 16 17 18 19
18 19 20 21 22 23 24      22 23 24 25 26 27 28      20 21 22 23 24 25 26
25 26 27 28 29 30 31      29 30                     27 28 29 30 31
command
C:\Users\username>python calendar.py
   December 2021
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
 
                                  2021
 
      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
             1  2  3       1  2  3  4  5  6  7       1  2  3  4  5  6  7
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       8  9 10 11 12 13 14
11 12 13 14 15 16 17      15 16 17 18 19 20 21      15 16 17 18 19 20 21
18 19 20 21 22 23 24      22 23 24 25 26 27 28      22 23 24 25 26 27 28
25 26 27 28 29 30 31                                29 30 31
 
       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                      1  2          1  2  3  4  5  6
 5  6  7  8  9 10 11       3  4  5  6  7  8  9       7  8  9 10 11 12 13
12 13 14 15 16 17 18      10 11 12 13 14 15 16      14 15 16 17 18 19 20
19 20 21 22 23 24 25      17 18 19 20 21 22 23      21 22 23 24 25 26 27
26 27 28 29 30            24 25 26 27 28 29 30      28 29 30
                          31
 
        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                         1             1  2  3  4  5
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       6  7  8  9 10 11 12
12 13 14 15 16 17 18       9 10 11 12 13 14 15      13 14 15 16 17 18 19
19 20 21 22 23 24 25      16 17 18 19 20 21 22      20 21 22 23 24 25 26
26 27 28 29 30 31         23 24 25 26 27 28 29      27 28 29 30
                          30 31
 
      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
             1  2  3       1  2  3  4  5  6  7             1  2  3  4  5
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       6  7  8  9 10 11 12
11 12 13 14 15 16 17      15 16 17 18 19 20 21      13 14 15 16 17 18 19
18 19 20 21 22 23 24      22 23 24 25 26 27 28      20 21 22 23 24 25 26
25 26 27 28 29 30 31      29 30                     27 28 29 30 31

In this example, we have used the month()month() function to get the calendar of a month. We have also used the calendar()calendar() function to get the calendar of a year.

Some Important Functions of Calendar Module

S.No.Function NameDescriptionExample
1calendar(year, w=2, l=1, c=6, m=3)Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces.calendar.calendar(2021)calendar.calendar(2021)
2month(year, month, w=2, l=1)Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines.calendar.month(2021, 12)calendar.month(2021, 12)
3monthcalendar(year, month)Returns a matrix representing a month’s calendar.calendar.monthcalendar(2021, 12)calendar.monthcalendar(2021, 12)
4prmonth(theyear, themonth, w=0, l=0)Prints a month’s calendar as returned by month()calendar.prmonth(2021, 12)calendar.prmonth(2021, 12)
5prcal(year, w=0, l=0, c=6, m=3)Prints the calendar for an entire year as returned by calendar()calendar.prcal(2021)calendar.prcal(2021)
6weekday(year, month, day)Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).calendar.weekday(2021, 12, 11)calendar.weekday(2021, 12, 11)
7weekheader(n)Returns a header containing abbreviated weekday names.calendar.weekheader(3)calendar.weekheader(3)
8weekrange(year, week, weekday)Returns the weekday (0 is Monday) and date of first day of the week containing the given day (1–31) in the given week (1–53) of the given year.calendar.weekrange(2021, 12, 11)calendar.weekrange(2021, 12, 11)
9isleap(year)Returns True if year is a leap year; otherwise, False.calendar.isleap(2021)calendar.isleap(2021)
10leapdays(y1, y2)Returns the total number of leap days in the years within range(y1, y2) (exclusive).calendar.leapdays(2021, 2022)calendar.leapdays(2021, 2022)
11month_nameAn array that represents the months of the year in the current locale.calendar.month_name[12]calendar.month_name[12]
12month_abbrAn array that represents the abbreviated months of the year in the current locale.calendar.month_abbr[12]calendar.month_abbr[12]
13day_nameAn array that represents the days of the week in the current locale.calendar.day_name[5]calendar.day_name[5]
14day_abbrAn array that represents the abbreviated days of the week in the current locale.calendar.day_abbr[5]calendar.day_abbr[5]
15setfirstweekday(weekday)Sets the first day of each week to weekday code.calendar.setfirstweekday(5)calendar.setfirstweekday(5)
16firstweekday()Returns the current setting for the weekday that starts each week.calendar.firstweekday()calendar.firstweekday()
17timegm(tuple)An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding.calendar.timegm((2021, 12, 11, 12, 0, 0, 0, 0, 0))calendar.timegm((2021, 12, 11, 12, 0, 0, 0, 0, 0))

Conclusion

In this article, we have learned about the Python standard library. We have also learned about the various modules in the Python standard library. We have also learned about the various functions in the Python standard library. When you are writing a Python program, you should always check if the functionality you are trying to implement is already available in the Python standard library. If it is available, then you should use it instead of writing your own code. This will save you a lot of time and effort. As you continue your journey in Python development, embracing modular programming practices will contribute to writing clean, maintainable, and efficient code. Happy coding!

Was this page helpful?

Let us know how we did