PY Module II
PY Module II
Fixing bugs in a program can be challenging, especially as the length of the code increases, which
is very often in the case of Machine Learning and Data Science projects. Multiple teams work on
the same project and sequentially develop different modules. Hence cleanliness and under stand
ability matter a lot.
To make debugging easier, developers working on different modules often divide their code into
smaller, manageable chunks called functions. This enables developers to identify the Function
where the bug is located easily. In Python, functions can be either user-defined or built in
functions
What is Function?
The function is a block of code defined with a name. We use functions whenever we need to
perform the same task multiple times without writing the same code again. It can take arguments
and returns the value.
Functions in Python provide organized, reusable and modular code to perform a set of specific
actions. Functions simplify the coding process, prevent redundant logic, and make the code easier
to follow. This topic describes the declaration and utilization of functions in Python.
Syntax:
def function_name(parameters):
"""docstring"""
statement1
statement2
...
...
return
To define the function, we use the def keyword, along with the function name.
The identifier rule must follow the function name.
The function block is started with the help of colon (:), and block statements must be at
the same indentation.
To return the value from the function, we use the return statement. A function can have
only one return statement involved in it.
Example:
def calculate(a,b):
calculate(200,100)
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of [Link] the basic structure of a function is finalized,
you can execute it by calling it from another function or directly from the Python prompt.
Following is the example to call printme() function −
calculate(2000,1000)
For example, Python has a random module that is used for generating random numbers
and data. It has various functions to create different types of random data.
print(randint(10, 20))
# Output 14
A function to receive one or more parameters (also called arguments) and use them for
processing inside the function block. Parameters/arguments may be given suitable formal
names.
The names of the arguments used in the definition of the function are called formal
arguments/parameters. Objects actually used while calling the function are called actual
arguments/parameters.
Example:
result = x * y
return result
if __name__ == “__main__”:
answer = multiply(3,4)
print(“Answer: “, ans/wer)
Built-in functions, such as help() to ask for help, min() to get the minimum value, print()
to print an object to the terminal,… You can find an overview with more of these functions
here.
User-Defined Functions (UDFs), which are functions that users create to help them out
Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword.
Built-in Functions:
Built-in functions are the functions that are already written or defined in python. We only need to
remember the names of built-in functions and the parameters used in the functions. As these
functions are already defined so we do not need to define these functions. Below are some built-
in functions of Python.
Program:
def get_length(word):
return len(word)
print(sorted_words)
User-Defined Functions:
The functions defined by a programmer to reduce the complexity of big problems and to use that
function according to their need. This type of functions is called user-defined functions.
User define functions are two types
return a + b
return a - b
return a * b
return a / b
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
In Python, a lambda function is a small, anonymous function that can take any number of
arguments but only have one expression. Lambda functions are also known as “anonymous
functions” because they don’t require a named function to be created.
syntax
add = lambda x, y: x + y
result = add(3, 5)
print(result)
numbers = [1, 2, 3, 4, 5]
print(squares)
When we define and call a Python function, the term parameter and argument is used to pass
information to the function.
parameter: It is the variable listed inside the parentheses in the function definition.
argument: It is a value sent to the function when it is called. It is data on which function performs
some action and returns the result.
s=a+b+c
return s
There are various ways to use arguments in a function. In Python, we have the following 4 types
of function arguments.
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments
We assign default values to the argument using the ‘=’ (assignment) operator at the time of
function definition. You can define a function with any number of default arguments.
The default value of an argument will be used inside a function if we do not pass a value to that
argument at the time of the function call. Due to this, the default arguments become optional
during the function call.
Example:
student('iphone', 12)
Keyword Arguments
Keyword arguments are those arguments where values get assigned to the arguments by their
keyword (name) when the function is called. It is preceded by the variable name and an (=)
assignment operator. The Keyword Argument is also called a named argument.
student("Suri", 14)
student(name='dasara', age=12)
Positional Arguments(functional)
Positional arguments are those arguments where values get assigned to the arguments by their
position when the function is called. For example, the 1st positional argument must be 1st when
the function is called. The 2nd positional argument needs to be 2nd when the function is called,
etc.
print(a - b)
add(50, 10)
add(10, 50 , 5)
Variable-length arguments
There is a situation where we need to pass multiple arguments to the function. Such types of
arguments are called arbitrary arguments or variable-length arguments.
We use variable-length arguments if we don’t know the number of arguments needed for the
function in advance.
We can declare a variable-length argument with the * (asterisk) symbol. Place an asterisk (*)
before a parameter in the function definition to define an arbitrary positional argument.
we can pass multiple arguments to the function. Internally all these values are represented in the
form of a tuple.
print('Average', avg)
This function works, but it’s limited to only three arguments. What if you need to calculate the
average marks of more than three subjects or the number of subjects is determined only at
runtime? In such cases, it is advisable to use the variable-length of positional arguments to write a
function that could calculate the average of all subjects no matter how many there are.
Arbitrary keyword arguments (**kwargs)
The **kwargs allow you to pass multiple keyword arguments to a function. Use the **kwargs if
you want to handle named arguments in a function.
def percentage(**kwargs):
sum = 0
sub_name = sub
sub_marks = kwargs[sub]
The order of keyword arguments is not important, but All the keyword arguments passed
must match one of the arguments accepted by the function.
Fruitful Functions
A function that returns a value is called fruitful function.
The functions that return a value are called “Fruitful Functions”. Every function after
performing its task it return the program control to the caller. This can be done implicitly.
This implicit return statemnet return nothing to the caller, except the program control. A
function can return a value to the caller explicitly using the “return” statement.
Syntax:
return (expression)
The expression is written in parenthesis that computes a single value. This return statement is
used for two things: First, it returns a value to the caller. Second, To end and exit a function andgo
back to the caller.
If we want a function to return a result to the caller of the function, we use the return statement.
For example, here we define two fruitful functions. The second one, circle area, calls the first
import math
def square(x):
return x ∗ x
In general, a return statement consists of the return keyword followed by an expression, which is
evaluated and returned to the function caller
For example:
Example:
Root=sqrt(25)
Abs(420)
abs(-420)
Example:
def area(r):
a=3.14*r*r
r=area(x)
4. When complete, return to the location in the program where the function was called.
Syntax:
def square(x):
return x*x
lambda x: x*x
f = lambda x: x*x
value = f(5)
Here, 'f' is the variable name to which the lambda expression is assigned.
Lambda functions contain only one expression and they return the result implicitly. Hence we
should not write any 'return' statement in the lambda functions.
Lambda functions cannot access variables other than in their parameter list.
filter()
map()
reduce().
Using the filter function, specific elements can be chosen from a list of elements. Any iterator,
such as lists, sets, tuples, etc., can be used as the sequence. The elements that will be chosen will
depend on a pre-defined constraint. There are two parameters -
Syntax:
filter(function, sequence)
Example:
Series = [23,45,57,39,1,3,95,3,8,85]
Function The map() function is similar to filter() function but it acts on each element of the
sequence and perhaps changes the elements.
Syntax:
map(function, sequence)
The 'function' performs a specified operation on all the elements of the sequence and the modified
elements are returned which can be stored in another sequence.
Example:
series = [23,5,1,7,45,9,38,65,3]
This function reduces the sequence of elements into a single element by applying a specific
condition or logic. To use the reduce function we need to import the functools module.
Syntax:
reduce(function, sequence)
Example:
return x + y
return x * y
data = [1, 2, 3, 4]
reduce(add, data)
10
reduce(multiply, data)
24
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable. The part of the program in which a variable can be accessed
is called its scope. The duration for which a variable exists is called its “Lifetime”. If a variable is
declared and defined inside a function its scope is limited to that function only. Itcannot be
accessed to outside that function. If an attempt is made to access it outside that
function an error is raised.
The scope of a variable determines the portion of the program where you can access aparticular
identifier. There are two basic scopes of variables in Python:
Global Scope -variables defined outside the function and part of main program
Local variable
A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function.
def myfunc():
x = 300
print(x)
myfunc()
Output
300
Global variable
Global variables are available from within any scope, global and local. A variable created outside
of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Output
300
300
def myfunc():
global x
x = 300
myfunc()
print(x)
Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller version of its task
until a final call is made which does not require a call to itself. Every recursive solution has two
major cases, which are as follows:
base case, in which the problem is simple enough to be solved directly without making any
further calls to the same function.
recursive case, in which first the problem at hand is divided into simpler sub parts.
Recursion utilized divide and conquer technique of problem solving.
Recursion vs Iteration:
Recursion is more of a top-down approach to problem solving in while the original problem is
divided into smaller sub-problems.
Iteration follows a bottom-up approach that begins with what is known and then constructing the
solution step-by-step.
Recursive solutions often tend to be shorter and simpler than non-recursive ones.
Code is clearer and easier to use.
Recursion uses the original formula to solve a problem.
It follows a divide and conquer technique to solve problems.
In some instances, recursion may be more efficient.
Modules_II
Till now, we were taking the input from the console and writing it back to the console to interact
with the user. Instead of that we can able use files as input or output.
Example:
def add(x, y):
return (x+y)
Modular programming refers to the process of breaking a large, unwieldy programming task into
separate, smaller, more manageable subtasks or modules.
Individual modules can then be cobbled together like building blocks to create a larger
application.
There are several advantages to modularizing code in a large application:
Simplicity: Rather than focusing on the entire problem at hand, a module typically focuses
on one relatively small portion of the problem.
Maintainability: Modules are written in a way that minimizes interdependency. This
makes it more viable for a team of many programmers to work collaboratively on a large
application.
Reusability: Functionality defined in a single module can be easily reused. This
eliminates the need to duplicate code.
Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.
What is namespace? Explain different types of name space and their Scope?
Every entity in python is considered an object. We give some names to every object like variable,
class, and function for identification. Often these names are known as identifiers in python. So,
the name is nothing but the identifier. All these names and where we use value are stored in the
main memory at a unique location. This location is known as space. So the location allocated to an
object name and its value is known as python namespaces.
Python also maintains its namespace that is known as a python dictionary. All namespaces in
python are like dictionaries in which names are considered as keys, and dictionary values are the
actual values associated with those names.
Example:
The telephone directory is a good real-time example for the namespace. If we try to search a
phone number of a person named SAHASRA, there are multiple entries, and it will be difficult to
find the right one. But if we know the surname of SAHASRA, we can see the correct number. In
this case, a person's name is a name or identifier in python, and space depends on the person’s
location.
1. Built-in Namespace
2. Global Namespace
3. Local Namespace
4. Create namespace
Built-in Namespace
When we run the Python interpreter without creating any user-defined function, class, or
module, some functions like input(), print(), type() are always present. These are built-in python
namespaces.
Example:
print(name)
we are using input() and print() without creating any function or without accessing any module
Global Namespace
When we create a module, it creates its namespaces, and these are called global
namespaces. The global namespace can access built-in namespaces.
Example:
x=10
def f1():
print(x)
f1()
The variable x is declared in a global namespace and has a global scope of variable in python.
Local Namespace
When we create a function, it creates its namespaces, and these are called local
namespaces. A local namespace can access global as well as built-in namespaces.
def f2():
f2()
print("Try printing var from outer function: ",var)
f1()
The variable var is declared in a local namespace and has a local scope of variable in python.
Create namespace
we have used a built-in namespace i.e. print() which is accessed by global and local namespace.
Also, we have created global namespace x and local namespace y.
Scopes in Python
The lifetime of the object depends on the scope of the object. Once the lifetime of the object
comes to the end scope of variables in python also ends. Scopes in python are nothing but the part
or portion of the program where namespace can be accessed directly.
Types of Scope
1. Local Scope
If we create a variable inside the function, then the scope of the variable in python is local.
[Link] Scope
If we create a variable inside the module, then that variable has a global scope in python.
3. Built-in Scope
When we don’t create any module or user-defined function and still can access the methods
like print(), type(), input(), then it is a built-in scope. When a script is run that created or loaded
built-in scope.
The variable is defined under the function, which is available only inside that function and
nested function.
create a module
In Python programming, to create a module simply define the functions, classes, and variables that
you want to place in the module and save the file with .py extension. For example, let's create a
module which performs all arithmetic operations.
Example:
return a + b
return a - b
defmul(a, b):
return a * b
return a / b
Module types
In Python, there are two types of modules.
Built-in Modules
User-defined Modules
Built-in Modules:
Built-in modules come with default Python installation. One of Python’s most significant
advantages is its rich library support that contains lots of built-in modules. Hence, it provides
a lot of reusable code. Some commonly used Python built-in modules are os, math, sys, random,
datetime, etc.
import datetime
now = [Link]()
print(now)
print([Link])
print([Link])
print([Link])
User-defined modules
The modules which the user defines or create are called a user-defined module. We can create
our own module, which contains classes, functions, variables, etc., as per our requirements.
return a + b
return a - b
return a * b
return a / b
A file is considered as a module in python. To use the module, you have to import it using the
import keyword. The function or variables present inside the file can be used in another file by
importing the module. This functionality is available in other languages, like typescript,
JavaScript, java, ruby, etc.
We need to load the module in our python code to use its functionality. Python provides three
types of statements as defined below.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
import math
print([Link](4))
import math
print([Link](0))
program.
return a + b
return a - b
return a * b
return a / b
import calculator
Syntax:
print(choice(fruits))
return a + b
return a - b
return a * b
return a / b
We use the from keyword, followed by random, to tell our program that we want to import a
specific function from the “random” module. Then, we usethe import keyword to tell our code
what function we want to import.
When using the from keyword to import a function, you do not need to write the function using
dot notation. As you can see above, instead of using [Link]() to access
the [Link]() function from the random module, we just use choice().
Syntax:
print(sqrt(25) )
print(tan(pi/6) )
print(pi)
print(tan(34))
print(factorial(5))
return a + b
return a - b
return a * b
return a / b
__name__ Attribute
The __name__ attribute returns the name of the module. By default, the name of the file
(excluding the extension .py) is the value of __name__attribute.
Example:
import math
print(math.__name__) #'math'
_doc__ Attribute
The __doc__ attribute denotes the documentation string (docstring) line written in a module code.
Example:
import math
print(math.__doc__)
Output:
_file__ Attribute
__file__ is an optional attribute which holds the name and path of the module file from which it is
loaded.
Example:
import io
print(io.__file__)
output: 'C:\\python37\\lib\\[Link]'
__dict__ Attribute
The __dict__ attribute will return a dictionary object of module attributes, functions and other
definitions and their respective values.
Example:
import math
print(math.__dict__)
Module Built-in Functions
Renaming a module
print("Addition is : ",Add(num1,num2))
Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.
Syntax:
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",[Link](a,b))
Import json
List = dir(json)
print(List)
reload(<module-name>)
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and sub packages and sub-sub packages, and so on.
Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and mod2.
Filename [Link]
def SayHello(name):
[Link]
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
The package folder contains a special file called __init__.py, which stores the package's content. It
serves two purposes:
The Python interpreter recognizes a folder as the package if it contains __init__.py file.
__init__.py exposes specified resources from its modules to be imported.
An empty __init__.py file makes all functions from the above modules available when this
package is imported. Note that __init__.py is essential for the folder to be recognized by Python
as a package.
Steps:
Example:
Def baz():
print('[mod3] baz()')
class Baz:
pass
print(sub_pkg1)
from..sub_pkg1.mod1import foo
foo()