Python Notes - Unit - 2
Python Notes - Unit - 2
Python Functions
In python, function is a block of code, and it will contain a series of statements to execute
whenever it is called in the program.
Functions are self-contained programs that perform some particular tasks. Once a function is
created by the programmer for a specific task, this function can be called anytime to perform that
task.
Suppose, we want to perform a task several times, in such a scenario, rather than writing code
for that particular task repeatedly, we create a function for that task and call it when we want to
perform the task. Each function is given a name, using which we call it. A function may or may
not retum a value.
There are many built-in functions provided by Python such as dir ( ) , len ( ) , abs ( ) , etc. Users
can also build their own functions, which are called user-defined functions. There are many
advantages of using functions:
a) They reduce duplication of code in a program.
b) They break the large complex problems into small parts.
c) They help in improving the clarity of code (i.e., make the code easy to understand).
d) A piece of code can be reused as many times as we want with the help of functions
Defining a Function
To define a function in python, you need to use the def keyword followed by the function name
and parentheses ( ). Following is the syntax of defining the function in python.
Function Syntax
In the above function syntax, we used different components to define the function.
1. The def keyword is used to indicate the start of the function.
2. function_name is the name to uniquely identify the function.
3. parameters are optional and these are useful to send values to the function.
4. The colon (:) symbol is used to indicate the start of the code block.
5. statement(s) inside the function body to perform the required tasks, and the statements must
follow the same indentation.
6. The return statement is useful to return a value from the function, and it’s optional.
To create a block of statements inside of the function body, you need to follow the same
indentation for all the statements.
def Statements
The def statement creates a function object and assigns it to a name. Its general format
is as follows:
def <name>(arg1, arg2,... argN):
<statements>
As with all compound Python statements, def consists of a header line followed by a block of
statements, usually indented (or a simple statement after the colon). The statement block
becomes the function’s body—that is, the code Python executes each time the function is called.
The def header line specifies a function name that is assigned the function object, along
1
with a list of zero or more arguments (sometimes called parameters) in parentheses. The
argument names in the header are assigned to the objects passed in parentheses at the point of
call.
Function bodies often contain a return statement:
def <name>(arg1, arg2,... argN):
...
return <value>
The Python return statement can show up anywhere in a function body; it ends the function call
and sends a result back to the caller. The return statement consists of an object expression that
gives the function’s result. The return statement is optional; if it’s not present, the function exits
when the control flow falls off the end of the function body. Technically, a function without a
return statement returns the None object automatically, but this return value is usually ignored.
Functions may also contain yield statements, which are designed to produce a series of values
over time
Types of Functions in Python
Below are the different types of functions in Python:
1. Built-in library function: These are Standard functions in Python that are available to
use.
2. User-defined function: We can create our own functions based on our requirements.
BUILT-IN FUNCTIONS
Built-in functions are the functions already defined in the Python programming language; we
can directly call them to perform a specific task. Every built-in function in Python performs
some particular task. For example, the Math module has some mathematical built-in functions
that perform tasks related to mathematics.
Some built-in functions provided in the Python programming language.
1. print() – Display Output
print("Hello Students")
print(10 + 20)
2. input() – Take Input from User
name = input("Enter your name: ")
print("Welcome", name)
3. len() – Find Length
text = "Python"
print(len(text))
4. type() – Check Data Type
x = 10
y = 3.5
z = "Hello"
print(type(x))
print(type(y))
print(type(z))
5. max() – Find Maximum Value
numbers = [10, 25, 5, 40]
print(max(numbers))
6. min() – Find Minimum Value
numbers = [10, 25, 5, 40]
print(min(numbers))
7. sum() – Add All Values
numbers = [10, 20, 30]
print(sum(numbers))
2
8. abs() – Absolute Value
print(abs(-15))
3
function. All the statements in the function are executed and then the program control is passed
to the statement following the one that called the function.
def fun1() def fun2() def fun3() def fun4()
…………….. …………….. …………….. ……………..
……………. ……………. ……………. …………….
fun2() fun3() fun4() …………….
…………….. …………….. …………….. ……………..
……………. ……………. ……………. …………….
In the above figure, func1() calls function named func2(). Therefore, func1() is known as the
calling function and func2() is known as the called function. The moment the compiler
encounters a function call, instead of executing the next statement in the calling function, the
control jumps to the statements that are a part of the called function. After called function is
executed, the control is returned back to the calling program.
It is not necessary that the func1() can call only one function, it can call as many functions as it
wants and as many times as it wants. For example, a function call placed within for loop or while
loop may call the same function multiple times until the condition holds true.
Function without Parameters:
A function without arguments, doesn't take any values as input when it is called. Instead, it
performs some computation based on its internal logic and returns a result.
def add_numbers():
a = 5 # Assigning values inside the function
b = 10
return a + b # Returning the sum
result = add_numbers() # Calling function without arguments
print("Sum:", result)
4
return 1
else: # This is the recursive case
return(x * factorial(x-1))
print(factorial(4))
Explanation:
Now let's analyse what is going on in the above recursive function.
First, when we pass the integer 4 into the function, it goes to the recursive case return
(x * factorial(x-1)) which will give us return(4 * factorial(3)).
Next, the function will call factorial(3) which will give us return(3 * factorial(2)) and it goes
on until we have x == 1 (the base case) and then the recursion will terminate. This means that if
we do not have a base case to stop the recursion, the function will continue to call itself
indefinitely. At the end we will have return(4 * 3 * 2 * 1)
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like
C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first assign a value to it. The
location where we can find a variable and also access it if required is called the scope of a
variable.
Python Local variable
Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function. Let’s look at how to make a local
variable.
Example:
def show():
x = 10 # local variable
print(x)
show()
# print(x) # ❌ error
Output:
Python Class
If we will try to use this local variable outside the function then let’s see what will happen.
Example:
def f():
# local variable
s = "Python Class"
print("Inside Function:", s)
f()
print(s)
Output:
name 's' is not defined
Example:
print x
Output:
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
2. Indentation Error:
This exception is raised when indentation (such as inconsistent use of tabs and spaces) is not
specified properly. When we write a program, Python uses indentation to nested blocks. Each
line in a block must have the same indentation level. If this rule is broken, an IndentationError
occurs.
Example:
def func():
print("This function has incorrect indentation.")
print("This line should be properly indented.")
#Calling the function to trigger the error func()
Output:
IndentationError: expected an indented block after function definition on line 2.
3. NameError:
This type of exception occurs when an identifier or variable is not found in the local or global
namespace. In other words, if non-existent identifier used, NameError exception occurs. Look at
the example below on it.
Example:
def func():
6
variable = 10
print("The value of the variable is:", varible)
func()
Output:
NameError: name 'varible' is not defined. Did you mean: 'variable'?
4. TypeError:
This type of exception occurs when invalid data type is supplied to an operation or function. It
can be caused due to several possible reasons.
They are:
Attempting to access elements within a string, list, or tuple using something other than an
integer. For example, if we try to access elements of a list or characters of a string using a non-
integer value (like a string, float, or any non-numeric value) as an index, Python raises an error,
specifically a TypeError.
When we pass the wrong number of arguments to a function or method.
Mismatch between elements in a format string and element passed for conversion.
Example:
def div(a, b):
result = a/b # Attempting to divide two values
return result
#Calling the function with incompatible types.
result = div("10", 2) # Dividing a string by an integer
print("Result:", result)
Output:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
5. ZeroDivisionError:
This type of exception occurs in a program when we attempt to divide a number by zero. Here's
an example code that raises a ZeroDivisionError:
Example:
def divide numbers(a, b):
result = a/b
return result
result = divide_numbers(8, 0)
print("Result:", result)
Output:
ZeroDivisionError: division by zero.
6. FileNotFoundError:
The FileNotFoundError exception occurs when we attempt to open or access a file that does not
exist.
The below is an example code that causes a FileNotFoundError.
Example:
f = open("nonexistent_file.txt", "r") # File does not exist
content = [Link]()
[Link]()
Output:
File not found. Error: [Errno 2] No such file or directory: 'nonexistent [Link]'.
7. IndexError:
7
The IndexError exception occurs when we try to access an element of a sequence (like a string,
list or tuple) using an invalid index number. Here's an example code that triggers an IndexError
without handling the exception:
Example:
numbers = [1, 2, 3]
result = numbers[4]
print("Result:", result)
Output:
IndexError: list index out of range
8. KeyError:
The KeyError exception occurs in a program when we try to access a dictionary key that does
not exist. Look at the below example. Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict['d']
print("Value:", value)
Output:
KeyError: 'd'
9. AttributeError:
The AttributeErrorexception occurs in the program when we attempt to access an attribute or
method that does not exist. If an AttributeError indicates that an object has NoneType, meaning
it is None. Look at the below example.
Example:
class Car:
def start(self):
print("Car started.")
c = Car()
[Link]()
Output:
AttributeError: 'Car' object has no attribute 'stop'
except ExceptionType:
# Code to handle the error
handle_error()
1. The “try” block contains the code that may cause an error.
2. The “except” block catches the error and executes alternative code.
3. Exception Type is optional and can be used to handle specific types of errors.
8
Example 1 Handling Division by Zero:
try:
num1 = 10
num2 = 0
result = num1 / num2 # This will cause ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
print("Program continues...")
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
except ValueError:
print("Error: Please enter a valid number!")
9
Python and OOP
Python is an object-oriented language since its beginning. It allows us to develop applications
using an Object-Oriented approach. In Python, we can easily create and use classes and objects.
An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-word entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating objects.
Basic Terms in OOP:
Class: Classes are defined by the user; the class provides the basic structure for an object. It
consists of data members and method members that are used by the instances (objects) of the
class.
Class Variable: A variable that is defined in the class and can be used by all the instances of
that class.
Data Member: A variable defined in either a class or an object; it holds the data associated with
the class or object.
Object: The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object, and almost
everything has attributes and methods. Object is an instance of a class. When we define a class,
it needs to create an object to allocate the memory.
Method: Methods are the functions that are defined in the definition of class and are used by
various instances of the class.
Abstraction: It refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a
list of abstract attributes such as size, weight, cost and functions to operate on these attributes.
Inheritance: In python, inheritance is the main concept of Object-Oriented Programming
(OOP), and it is helpful to inherit all the properties and methods from one class to another class.
To implement the inheritance process in python, you need to define the child class with
parentheses ( ) by including the base class.
Polymorphism: Polymorphism means the ability to take more than one form. The process of
making an operator to exhibit different behaviours in different instances is known as operator
overloading.
Defining a Class:
A class can be defined as a blue print or a previously defined structure from which objects are
made. It can also be defined as a group of objects that share similar attributes and relationships
with each other.
For example:
1. Fruit is a class, and apple, mango and banana are its objects. The attributes of
these objects can be color, taste, etc.
2. Vehicle is a class and car, scooter, bus, truck, etc., can be its objects. The
attributes of these objects can be speed, brake, power of engine, etc.
In Python, a class is defined by using a keyword class. After that, the first statement can be a
docstring (optional) that contains the information about the class. Now, in the body of class, the
attributes are defined. These attributes can be data members or method members.
In Python, as soon as we define a class, the interpreter instantly creates an object that has the
same name as the class name. Although, we can create more objects of the same class. With the
help of objects, we can access the attributes defined in the class.
Syntax
class class name:
‘This is docstring which is optional'
class_suite
A new local new space is created by a Class, where all its attributes (data or function) are
defined. As soon as the class is defined, a new class object is created with same name, which
allows access to the different attributes, also to instantiate new object of that class.
10
The class has a documentation string which can be accesed via ClassName_doc_
The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example:
class Dog:
sound = "bark"
# Create an object from the class
d = Dog()
# Access the class attribute
print([Link])
Inheritance:
Inheritance is a very important concept in OOP. It is used to inherit the properties and
behaviours of one class to another. The class that inherits another class is called a child and the
class that gets inherited is called a base class or parent class. It means the reusability of code. It
is the capability of a class to derive the properties of another class that has already been created.
Let us look at an example
1. Vehicle is a class that is further divided into two subclasses, automobiles (driven by
motors) and pulled vehicles (driven by men). Therefore, vehicle is the base class and
automobiles and pulled vehicles are its subclasses. These subclasses inherit some of the
properties of the base class vehicle.
2. Truck and car are the subclasses of the class automobile that is the base class for them.
They inherit some of the properties of base class automobiles. Similarly, the rickshaw and
bullock cart are the subclasses of pulled vehicles that serves as the base class for them.
The main advantage of inheritance in the context of programming is that the code can be
written once in the base class and then reused repeatedly in the subclasses.
Inheritance:
11
Inheritance is a fundamental concept in object oriented programming (OOP) that allows one
class (child or derived class) to acquire the properties and methods of another class (parent or
base class) or promotes code reusability and helps in building a hierarchical classification.
Types of Inheritance in Python:
Python supports various types of inheritance.
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hybrid Inheritance
Single Inheritance: One base class and one derived class are involved in single inheritance. The
characteristics and methods of the base class are passed down to the derived class. It enabling
code reusability and addition of new features to existing code.
B
Example Program:
Class Animal:
Single Inheritance
def speak(self):
print(“Animal Speaks”)
#Child Class
Class Dog(animal):
Def bark(self):
Print(“Dog barks”)
Multiple Inheritance: Multiple Inheritance entails more than one base class and one derived
class. All of the base classes characteristics and methods are passed down to the derived class. It
allows the derived class to aggregate and use functionality from several sources.
A B
C
Example:
Multiple Inheritance
12
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
B
Example: Multilevel Inheritance
class Animal:
def speak(self):
print("Animal Speaking") C
Single Inheritance
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
Hybrid Inheritance: The term hybrid inheritance refers to the combination of multiple
inheritance and multilevel inheritance. It enables a customize class hierarchy with a mix of
features from several inheritance types. When a class needs to inherit from numerous base
13
Class A Class A
classes and participate in a multilayer inheritance chain, this type of inheritance is beneficial.
Example:
class A:
def method_a(self):
print('Method A')
class B(A):
def method_b(self):
print('Method B')
class C(A):
def method_c(self):
print('Method C')
class D(B,C):
def method_d(self):
print('Method D')
My_object=D()
My_object.method_a() # Output: Method A
My_object.method_b() # Output: Method B
My_object.method_c() # Output: Method C
My_object.method_d() # Output: Method D
14
Polymorphism in Python
Polymorphism is one of the key concepts of Object-Oriented Programming (OOP). The word
"polymorphism" is derived from Greek, where "poly" means many and "morph" means forms. In
simple terms, polymorphism allows the same function or method to have different behaviors
based on the object it is acting upon.
Types of Polymorphism in Python
1. Method Overriding
2. Operator Overloading
3. Method Overloading
Method Overriding
Method overriding occurs when a child class provides a specific implementation of a method
that is already defined in its parent class.
Example:
class Animal:
def speak(self):
return "Animal makes a sound"
class Dog(Animal):
def speak(self):
return "Dog barks"
class Cat(Animal):
def speak(self):
return "Cat meows"
# Creating objects
a = Animal()
d = Dog()
c = Cat()
Operator Overloading
Python allows us to redefine how operators like +, -, *, etc., work for user-defined objects.
Example:
class Student:
def __init__(self, marks):
[Link] = marks
s1 = Student(80)
s2 = Student(90)
15
Method Overloading
Python does not support method overloading like other languages (such as Java or C++), but we
can achieve similar behavior using default arguments.
Example:
class Calculator:
def add(self, a, b, c=0):
return a + b + c
calc = Calculator()
print([Link](10, 20)) # Output: 30
print([Link](10, 20, 30)) # Output: 60
Module in Python:
A module in Python is a file containing Python code (functions, classes, or variables) that can be
reused in other programs. It helps in code reusability and organization. A module is a file that
will contain a set of objects such as functions, variables, classes, etc., to use in your applications.
The modules are useful to reduce the code redundancy by keeping the common functionalities
such as functions, variables, etc., in one place and use it in any interpreter session or python
script.
Creating a Module:
In python, we can create a module by writing the following code in the [Link] file.
Import Module:
In python, you can import the module by using the import keyword. To use the module
(samplemodule) that we created in any python script or interpreter, you need to use an import
statement like as shown below.
import samplemodule
16
Python Built-in Modules:
The module is a file that will contain a set of functions, variables, classes, etc., to use in your
applications. Python has a set of built-in modules such as math, os, sys, etc., to use in any
python script file. The built-in modules will load automatically whenever the interpreter starts,
and these modules are available as a part of python libraries.
To see the list of all available built-in modules, execute the help('modules') command in the
python console as shown below.
Following is an example of getting the details about the math module in python.
import math
help(math)
time Module:
The time module in Python provides functions to work with time-related operations like
measuring execution time, delaying execution, and getting the current time.
import time
17
Getting the Current Time ([Link]())
Returns the current time as the number of seconds since January 1, 1970 (Epoch Time).
import time
print([Link]())
18