Built-in Functions, Modules and packages

 Built-in Functions


A function is a named sequence of statement(s) that performs a computation. It contains line of code(s) that are executed sequentially from top to bottom by Python interpreter.They are the most important building blocks for any software development in Python.

Built in functions are the function(s) that are built into Python Standard Library  and can be accessed directly.Functions usually have arguments and return a value.

Some built in functions are given below with examples. Refer python documentation for more details.

https://docs.python.org/3.8/library/functions.html

abs(x) returns the absolute value of x . abs(-45) will return 45
max(x,y,z) returns the maximum of x,y,z . max(10,20,30) will return 30
min(x,y,z) returns the minimum of x,y,z . min(10,20,30) will return 10
divmod(x,y) returns both the quotient and remainder . divmod(14,5) will return (2,4)
cmp(x,y) returns 0 if x==y , 1 if x>y and -1 if x<y
round(x,n) round x to n digits. round(3.14567,2) will return 3.15
range(start,stop,step) will return a list from start to stop-1 with an increment of step.
range(10) will return [0,1,2,…9] range(1,10,2) will return [1,3,5,7,9]
type(x) will return the type of the variable object x.
dir(x) will display the details of the object x.
len(x) will return the length of the object.
int(),float(),str(),bool(),chr(),long() these functions can be used for type conversions.
bin(x), oct(x), hex(x) these functions will convert the decimal number x into corresponding base.

Modules

When our program grows bigger, it is a good idea to break it into different modules.

A module is a file containing Python functions, classes, and variables. A module can also include runnable code. Python modules have a filename and end with the extension .py.

We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide re usability of code.

We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.
Example: Suppose we have a file named mymodule.py with the following content:

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b
Basic Import:
import mymodule

print(mymodule.greet("Alice"))  # Output: Hello, Alice!
print(mymodule.add(2, 3))       # Output: 5
Import Specific Functions or Variables:
from mymodule import greet, add

print(greet("Bob"))  # Output: Hello, Bob!
print(add(4, 5))     # Output: 9

Import with an Alias:
import mymodule as mm

print(mm.greet("Charlie")) # Output: Hello, Charlie!
print(mm.add(3, 6)) # Output: 9


Packages
package is a collection of modules organized in directories that include a special file called __init__.py. The __init__.py file can be empty or execute initialization code for the package. Packages allow for a hierarchical structuring of the module namespace.

Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.

Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.

Creating a Package

Directory Structure:
mypackage/
    __init__.py
    module1.py
    module2.py

module1.py:
def foo():
    return "foo from module1"

module2.py:
def bar():
    return "bar from module2"

__init__.py:
from .module1 import foo
from .module2 import bar

Importing a Package

Basic Import:
import mypackage

print(mypackage.foo())  # Output: foo from module1
print(mypackage.bar())  # Output: bar from module2

Import Specific Modules or Functions:
from mypackage import module1, module2

print(module1.foo())  # Output: foo from module1
print(module2.bar())  # Output: bar from module2

Import Functions from Modules Directly:
from mypackage.module1 import foo
from mypackage.module2 import bar

print(foo())  # Output: foo from module1
print(bar())  # Output: bar from module2

Various Ways to Import a Package

Import the Entire Package:
import mypackage
Import Specific Module from a Package:
from mypackage import module1, module2
Import Specific Functions or Classes from a Module within a Package:
from mypackage.module1 import foo
from mypackage.module2 import bar
Import with an Alias:
import mypackage.module1 as m1
import mypackage.module2 as m2

print(m1.foo())  # Output: foo from module1
print(m2.bar())  # Output: bar from module2
Wildcard Import (Not Recommended): 
This method imports all functions and classes from a module.
from mypackage.module1 import *

Advantages of Using Modules and Packages
  • Code Re-usability: Write a function or class once and reuse it in multiple programs.
  • Namespace Management: Avoid naming conflicts by organizing code into modules and packages.
  • Maintainability: Makes code easier to maintain and update.
  • Scalability: Facilitates the growth of the codebase by organizing it into manageable pieces.
Understanding how to create and import modules and packages is fundamental to writing clean, organized, and scalable Python code.

Built-in Modules and Packages

Python comes with a rich standard library that includes numerous built-in modules and packages. These built-in modules and packages provide pre-written functions and classes that can be used to perform common tasks without having to write the code from scratch. Below are some of the key built-in modules  in Python:
sys: Provides access to some variables used or maintained by the Python interpreter and to functions that interact strongly with the interpreter.
import sys
print(sys.version)  # Prints the Python version
os: Provides a way of using operating system-dependent functionality like reading or writing to the file system.
import os
print(os.getcwd())  # Prints the current working directory
math: Provides access to mathematical functions and constants.
import math
print(math.sqrt(16))  # Prints 4.0
datetime: Supplies classes for manipulating dates and times.
import datetime
print(datetime.datetime.now())  # Prints the current date and time
random: Implements pseudo-random number generators for various distributions.
import random
print(random.randint(1, 10))  # Prints a random integer between 1 and 10

Note:The Python 3.12 standard library contains over 300 modules. This number changes from time to time as modules are added or removed. The standard library is a collection of modules that are included with all Python installations. These modules provide a wide range of functionality, from basic data types and functions to more advanced features like networking and web development.
In addition to the standard library, there are thousands of third-party modules available for Python. These modules can be used to add new features to Python or to extend the functionality of existing modules.

Python Module Search Path

While importing a module, Python looks at several places. Interpreter first looks for a built-in module. Then(if built-in module not found), Python looks into a list of directories defined in sys.path. The search is in this order.
The current directory.
PYTHONPATH (an environment variable with a list of directories).
The installation-dependent default directory.
>>> import sys 
>>> sys.path

The dir() built-in function

We can use the dir() function to find out names and functions that are defined inside a module.
>>>import math
>>>dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Using Built in module
Example: math module
For example, we can import the math module by typing the following line:
import math

We can use the module in the following ways:
import math
print("The value of pi is", math.pi)
The value of pi is 3.141592653589793

Import with alias name
import math as m
print("sqr root of 25 is", m.sqrt(25))
sqr root of 25 is 5

We have renamed the math module as m. This can save us typing time in some cases.Note that the name math is not recognized in our scope. Hence, math.sqrt(25) is invalid, and m.sqrt(25) is the correct implementation.

We can import specific functions or constants from a module without importing the module as a whole. Here is an example.
# import only pi from math module
from math import pi
print("The value of pi is", pi)


We can also import multiple attributes as follows:
from math import pi, e
pi
3.141592653589793
e
2.718281828459045


We can import all names(definitions) from a module using the following construct:
from math import * # import all names from the standard module math
math.pow(2,3)
8
You can also get help of a particular function using the help() function
help(math.sqrt)

The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a "singleton" - they are initialized only once.
Click the following link to know various Python modules

Using packages
numpy is a popular package for numerical computations

import numpy.linalg as linalg
matrix = np.array([[1, 2], [3, 4]])
det = linalg.det(matrix)  # Determinant of the matrix

As of May 2024, there are over 530,000 Python packages available on PyPI, the official online software repository for Python. Packages are a key reason why Python is such a powerful and widely used programming language. They allow developers to reuse code and share functionality, which can save time and effort.
Some of the most popular Python packages include:
NumPy: A package for scientific computing with Python.
Pandas: A package for data analysis and manipulation.
Matplotlib: A package for data visualization.
Scikit-learn: A package for machine learning.
TensorFlow: A package for deep learning.
PyTorch: A package for deep learning.
Requests: A package for HTTP requests.
Beautiful Soup: A package for web scraping.
Flask: A package for web development.
Django: A package for web development.

Installing Third-Party Packages

To install third-party packages, you can use pip, which is the package installer for Python. Here are some common commands:

Install a Package:pip install package_name
Upgrade a Package:pip install --upgrade package_name
Uninstall a Package:pip uninstall package_name
List Installed Packages:pip list


Sample Programs using Python built-in functions and modules

Find the number of digits in the factorial of the number 100. ( university question)
import math
nd=len(str(math.factorial(100)))
print("Number of digits in the factorial of 100=",nd)

Converting a decimal number into different basis
print("Enter a decimal number..")
x=int(input())
print("Binary is=",bin(x))
print("Oct is=",oct(x))
print("Hex is=",hex(x))

Print a particular month/year calendar
import calendar
y=int(input("Enter year--"))
m=int(input("Enter month--"))
print(calendar.month(y,m))

Write a Python program to find distance between two points (x1,y1) and (x2,y2) ( university qn)
import math
x1=int(input('Enter x1:'))
y1=int(input('Enter y1:'))
x2=int(input('Enter x2:'))
y2=int(input('Enter y2:'))
dis=math.sqrt(math.pow(x2-x1,2)+math.pow(y2-y1,2))
print("distance",dis)

Key Points

  • Most of the power of a programming language is in its libraries.

  • A program must import a library module in order to use it.

  • Use help to learn about the contents of a library module.

  • Import specific items from a library to shorten programs.

  • Create an alias for a library when importing it to shorten programs.

Comments

Popular posts from this blog

Algorithmic Thinking with Python UCEST 105- KTU First Semester BTech Course 2024 scheme notes pdf - Dr Binu V P 9847390760

Heuristic Method

Problem-Solving Strategies