Python - Functions, Methods, Modules, Packages

In this we will discuss about Functions, Modules, Packages of Python
Function: reusable code to achieve a specific purpose
Method: Function associated with a specific type like str, list etc. Methods of specific type can be known by using "help(type)". E.g., help(str)

Functions:

Function is a code to perform a specific task.
Execution of function is called as calling a function.
Python has many built-in functions and some of the common functions are listed below along with minimal description of what that function will do

  • print() - to print a message 
  • type() - to know the data type
  • min() - to know the minimum value
  • max() - to know the maximum value
  • range() - specifically used with for loop -- range(start_number, max_number+1). The range(n) function generates a sequence of numbers from 0 up to but not including n
  • sum() - to perform addition 
  • round(value, ndigits) - usage round(value,2) will print value up to 2 decimal places








  • round(value, ndigits) can also take negative number for ndigits
    • -1 will do rounding for tens
    • -2 will do rounding for hunders
    • -3 will do rounding for thousands


  • len() - to know the length of str/number of elements in list. len() doesn't work with Floats, Integers and Booleans
  • sorted()  - sort in ascending order
  • help(function) - provides info on how to use a function. help() can also be used on datatypes

Nested function - calling a function within a function. In below screenshot, we are calling sum function within round function. 














How to define/create a function?
def function_name():
    code

def hi(): // here we have declared a function with name "hi"
    print("Hello World from Python Function")

How to execute (call) a function? 
Executing a function is also known as calling a function and we will do by writing function name followed by parenthesis as shown here -> function_name()
For example, to call a function with name "hi", we will write -> hi()

Function signature refers to the part of the function that defines the function's name, parameters, and the types of values it accepts (optional) and returns (optional)


Methods:
Methods are Functions associated with a specific type/object like str, list etc. 
Methods of specific type can be known by using "help(type)". E.g., help(str)
Generic syntax to invoke/call a method is by writing type/var.method(). E.g. print(str.upper("john"))
Here, we are converting a string type to upper case using method "upper" and printing using print function

Modules:

These are Python scripts which 
  • contain functions and attributes
  • can contain other modules and 
  • are files ending in .py
  • Ideally module can be considered a single python file
Python has several built-in modules and this helps in avoiding rewriting code.
Some of the most popular Modules are
  • os - for interpreting and interacting with OS
  • collections - advanced data structure types and functions
  • string - to perform string operations
  • logging - to log information when testing or running software
  • subprocess - to run terminal commands
To use the code from a module, we use "import" keyword as shown below
import <module_name>
import os

Once a Module is imported, we can use it as shown below
import os
os.getcwd()  -- to get current dir
os.chdir(target_dir) -- to change dir to target_dir

Listing the functions in a module
documentation
help(module_name)

Modules have attributes which will have values and will NOT HAVE parenthesis where as functions will perform tasks and has parenthesis
os.environ  (here os is the module and environ is the attribute)
string.ascii_uppercase - which will allow to print all ASCII upper case characters

Importing a full module without using it will cause more memory consumption. To avoid this we can import specific function from module.

from <module_name> import <function_name>
from <module_name> import <function_name1>, <function_name2>
from datetime import date


Packages:

A package is a directory/collection of scripts. 
Each script is a module and can also be called as Library.
Each script specify functions, methods, types aimed at solving a problem
These are publicly available and free. Need to be downloaded from PyPI, which is a directory of packages. 

Few popular Packages and their purpose are listed below
  1. panda - data cleaning, manipulation and analysis.
  2. NumPy - to work with arrays
  3. Matplotlib - data visualization
  4. scikit-learn - machine learning

Packages should be downloaded and installed as shown below before they can be used like modules by importing.

We can use "pip (package maintenance system for Python)", to install Packages on our local. pip can be installed using two ways as described in this link   
  1. ensurepip
  2. get-pip.py
Once "get-pip.py" is downloaded, run "python3 get-pip.py" run from Terminal to install pip.

Installing a package:
python3 -m pip install <package_name>
python -m pip install <package_name>
python3, python are used to execute code from terminal
pip means Preferred Installer Program which is used to install packages


Installing a package(panda) and using it by importing
Panda is package is used for data cleaning, manipulation and analysis.
python3 -m pip install pandas
import pandas

The problem with above import is we have to use "pandas" everywhere wherever we refer it and it is like more words/code. To address we can import using an alias

python3 -m pip install pandas
import pandas as pd (here pd is the alias for pandas)

After importing pandas, we can create a DataFrame(tabular form) and work with it. Let's say if we have a dictionary type, called authors, we can convert it to a  DataFrame as below.

authors_df = pd.DataFrame(sales)
authors_df 

 

I have attempted to install pip and no luck. I have tried work arounds as per below and was able to install it successfully on Linux Server. Below are the commands along with the screenshot.

  • cat /etc/redhat-release
  • python3 --version
  • python -m pip install pandas
  • python3 -m pip install pandas
  • python -m ensurepip --default-pip
  • python3 -m pip install pandas



























If we have a dictionary with name authors, using pandas, the same authors dictionary can be seen as DataFrame using below commands.
  • import pandas as pd
  • <dictionary>_df = pd.DataFrame(<dictionary>) (to convert Dictionary to DataFrame)
    • E.g. authors_df = pd.DataFrame(authors)
  • <dictionary>_df (to view the DataFrame)
    • E.g. authors_df

Type of authors can be verified using type() which returns "pandas.core.frame.DataFrame" as shown below.

type(authors_df)
<class 'pandas.core.frame.DataFrame'>

 
Reading from a CSV file
  • import pandas as pd
  • authors_df = pd.read_csv(filename.csv)
  • authors_df
We can preview the DataFrame using head() --- DataFrame.head() to print first 5 rows
E.g. authors_df.head()


Below is the comparison between Function, Method, Module and package

Aspect Function Method Module Package
Definition A block of reusable code that performs a specific task. A function that is associated with an object (class). A file containing Python code (functions, classes, etc.). A directory that contains related modules and an __init__.py file.
Defined Using def keyword. def keyword, inside a class. .py file with Python code. A directory containing .py files and an __init__.py file.
Usage Called with arguments and returns a result. Called on an object using dot notation (object.method()). Imported using the import keyword. Imported using from package import module.
Example def add(x, y): return x + y class Calculator: def multiply(self, x, y): return x * y import math_operations from my_package import module1
Characteristics Can be standalone. Always requires an object instance (i.e., self). Contains functions, classes, and runnable code. A directory of related modules, can include sub-packages.
Location Defined anywhere in a script. Defined inside a class. In a .py file. In a directory structure.

No comments:

Post a Comment