SlideShare a Scribd company logo
UNIT 2: FUNCTIONS IN PYTHON
1
Prof. JISHNU M S
Assistant Professor
Kristu Jayanti College(Autonomous),
Bengaluru
FUNCTION
JISHNU M S 2
 Function in Python is a reusable block of code that performs a single, specific
and well defined task.
 It allows you to encapsulate a set of instructions into a single unit, which you
can then call by its name whenever you want to execute that set of instructions.
WHY FUNCTION ?
 Code Reusability
 Modularity
 Easy Debugging
 Less Development Time
HOW FUNCTION WORKS ?
JISHNU M S 3
SYNTAX OF FUNCTION DEFINITION
JISHNU M S 4
EXAMPLE OF FUNCTION DEFINITION
JISHNU M S 5
 In Python, you can define a function using the def keyword
followed by the function name, a set of parentheses
containing any parameters the function takes, and a colon.
 The function body is indented and contains the code that
defines what the function does.
 You can also include a return statement to send a value back
as the result of the function's execution.
EXAMPLE 1
JISHNU M S 6
# function declaration
def function():
print(“Hello world”)
# calling function
function() # function call
EXAMPLE 2
JISHNU M S 7
def greet(name):
return "Hello, " + name + "!"
# Calling the function
message = greet(“BCAA ")
print(message) # Output: Hello, BCAA!
The greet function takes a single parameter name and returns a greeting message
FUNCTION PARAMETRES
JISHNU M S 8
The name of the function while calling and the number of
arguments must match with the function definition.
If there is a mismatch in number of parameters passed
and declared, then an error will be returned.
If the data type of the parameter passed does not match
with that of the function, then an error is generated.
EXAMPLE 3
JISHNU M S 9
# function declaration
def add(x,y):
return x+y
# main function
m=10
n=4
print(add(m,n))
OR
z=add(m,n)
print(z)
FUNCTION PARAMETRES
JISHNU M S 10
TYPES OF FUNCTIONS IN PYTHON
JISHNU M S 11
ANONYMOUS FUNCTIONS
 Anonymous functions are known as "lambda" functions.
 Lambda functions are not declared using def keyword. Instead lambda is used.
 A lambda function is a small, inline function that doesn't have a formal name like
a regular user-defined function.
 Lambda functions are often used for short, simple operations that can be defined
in a single line of code.
 Any number of arguments can be supplied to lambda functions, but it must
contain only a single expression.
JISHNU M S 12
ANONYMOUS FUNCTIONS
 The syntax for creating a lambda function is as follows:
 Here's a basic example of a lambda function that adds two numbers:
JISHNU M S 13
lambda arguments : expression
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
JISHNU M S 14
ANONYMOUS FUNCTIONS
1. Lambda functions have no name
2. Lambda function cannot access variables other than those in their parameter list.
3. Lambda functions can take N number of arguments
4. Lambda functions does not have any return statement
5. It could have only a single expression
 Lambda functions are typically used when you need a quick function for a short task,
like passing a function as an argument to another function, working with higher-order
functions like map(), filter(), or sorted(), or creating simple key functions for sorting.
 Here's an example of using a lambda function with the sorted() function:
points = [(3, 5), (1, 9), (8, 2)]
sorted_points = sorted(points, key=lambda point: point[1]) #Sorting by the second element of each tuple
print(sorted_points) # Output: [(8, 2), (3, 5), (1, 9)]
 Lambda functions can be useful in situations where defining a full named function might
be unnecessary due to the function's simplicity.
 However, for more complex or larger functions, it's generally better to use regular user-
defined functions for clarity and maintainability.
JISHNU M S 15
JISHNU M S 16
RECURSIVE FUNCTIONS
Recursive function is a function that calls itself as part of its execution.
Recursive functions are used to solve problems that can be broken down into smaller
instances of the same problem.
Each recursive call works on a smaller piece of the problem until it reaches a base
case where a direct solution can be obtained without further recursion.
Recursive functions can be a powerful tool for solving certain types of problems, but
they should be designed carefully to avoid infinite recursion and excessive function
calls.
17
RECURSIVE FUNCTION EXAMPLE
 Suppose we want to calculate the factorial value of an integer [n! = n * (n-1)!]
JISHNU M S
def factorial(n):
if n == 0:
return 1
else
return n * factorial (n-1)
print(factorial(5)) # output will be 120
calculating the factorial of a non-negative integer n:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5) # 5! = 5 * 4 * 3 * 2 * 1 = 120
print(result) # Output: 120
The factorial function calls itself with a smaller
value of n until it reaches the base case where n is 0.
This base case returns 1, and the function then starts
"unwinding" the recursive calls, multiplying each
value of n until the original call is complete.
 When creating recursive functions, it's important to define the base case(s) that will
terminate the recursion and prevent infinite loops.
 Without a proper base case, the function would keep calling itself indefinitely and
eventually lead to a "RecursionError" due to exceeding the maximum recursion depth.
JISHNU M S 18
Calculating the Fibonacci sequence:
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
result = fibonacci(6) # Fibonacci sequence: 0, 1, 1, 2, 3, 5, ...
print(result) # Output: 8
The fibonacci function
calculates the nth number in the
Fibonacci sequence by
recursively summing the
previous two numbers.
 Recursive functions can be elegant solutions for certain problems, but they can also be
less efficient than iterative approaches in terms of memory and performance.
 When using recursion, it's important to understand the trade-offs and choose the
appropriate approach based on the problem's requirements.
JISHNU M S 19
JISHNU M S 20
USER-DEFINED FUNCTIONS IN PYTHON
 User-defined functions in Python are functions that you create yourself to perform
specific tasks according to your needs.
 They allow you to encapsulate a block of code into a reusable unit, making your code
more organized and modular.
 To define a user-defined function in Python, you use the def keyword followed by the
function name, a set of parentheses containing any parameters the function takes (if
any), and a colon (:).
 The function body is indented and contains the code that defines what the function
does.
 You can also include a return statement to send a value back as the result of the
function's execution.
Here's the basic syntax for defining a user-defined function:
Here's an example of a simple user-defined function:
JISHNU M S 21
def function_name(parameters):
# Function body
# Code to perform the task
return result # Optional
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
JISHNU M S 22
FUNCTIONS ARGUMENTS
 You can call a function by using this types of
formal parameters
JISHNU M S 23
1. REQUIRED ARGUMENTS
 Arguments must be passed on to a function in correct order.
 The number of arguments passed to a function must match with the number of
arguments specified in the function definition
def prd ( a , b):
prd = a * b
return prd
product = prd ( 12, 2)
print ( product ) # output will be 24
JISHNU M S 24
2. KEYWORD ARGUMENTS
 A keyword argument helps to identify arguments by specifying the name of the
parameter.
 The order of the keyword argument is not important.
 The keyword arguments passed must match with one of the arguments of the
accepting function.
 It makes the program code less complex and easy to understand
JISHNU M S 25
2. KEYWORD ARGUMENTS
def student ( name, course, fees):
print(“Name: “, name)
print(“Course: “, course)
print(“Fees: “, fees)
n = “Ashok”
c = “BCA”
f = “30000”
Student ( fees=f, name=n, course=c)
# output will be
Name: Ashok
Course: BCA
Fees : 30000
JISHNU M S 26
3. DEFAULT ARGUMENTS
 It allow to specify a value for a parameter
 This allow to call a function with less number of arguments defined.
 Any number of default arguments can be defined.
 Non default argument cannot be followed by the default arguments
def student ( name, course = “BCA):
print(“Name: “, name)
print(“Course: “, course)
Student ( name= “Ashok”)
# output will be
Name: Ashok
Course: BCA
JISHNU M S 27
4. VARIABLE - LENGTH ARGUMENTS
 In cases where it is not known in prior how many arguments will be passed to a
function , python allows to make function call with arbitrary number of arguments
 An asterisk (* ) symbol is used before the parameter name.
def vlen ( course, sem, *sub_mark):
print(“Course: “, course)
print(“Sem: “, sem)
for p in sub_mark:
print(“sub_mark: “, sub_mark)
vlen (“BCA”, “fifth”, 100, 99, 90)
# output will be
Course: BCA
Sem: fifth
Sub_mark: 100
Sub_mark: 99
Sub_mark: 90
28
INTRODUCTION TO MODULES
 A module is a .py extension file which has the definitions of all the functions,
classes, and variables that can be used in other Python programs.
 Modules provide a way to organize your code and make it more modular,
reusable, and maintainable.
 In simple terms we can consider a module to be same as the code library or file
that contains a certain function that can be included in the application.
 The program which want to use functions & variables defined in the module will
use import keyword to link or import the module or the .py file
JISHNU M S
29
INTRODUCTION TO MODULES
 Python has a rich collection of built-in modules, and you can also create your own
custom modules to encapsulate related functionality.
 If we need to organize the code logically one of the best method is to use modules.
JISHNU M S
JISHNU M S 30
Introduction to working with modules in Python:
1. Built-in Modules: Python comes with a set of built-in modules that provide various
functionalities. Some common examples include:
a. math: Provides mathematical functions and constants.
b. random: Generates random numbers.
c. datetime: Manipulates dates and times.
d. os: Interacts with the operating system, like reading directories and files.
e. sys: Provides access to system-specific parameters and functions.
JISHNU M S 31
2. Importing Modules: To use functions, classes, or variables from a module, you need to
import the module into your code. The import statement is used for this purpose. For
example:
import math
print(math.sqrt(16)) # Output: 4.0
You can also use the from keyword to import specific items from a module:
from math import sqrt
print(sqrt(16)) # Output: 4.0
JISHNU M S 32
3. Creating Custom Modules: You can create your own modules by creating a .py file and
placing your Python code inside it. For example, if you create a file named my_module.py
with the following content:
Module 1: demo.py Module 2
def disp (name):
print(“Hello”, +name)
import demo
demo.disp(“BCAA”)
JISHNU M S 33
4. Package:
 A package is a collection of related modules organized in a directory hierarchy. It
includes a special __init__.py
 __init__.py file that makes Python treat the directory as a package.
 Packages allow you to organize related modules into a coherent structure.
JISHNU M S 34
5. Third-party Modules:
 Python has a vast ecosystem of third-party modules that you can install and use to
extend your code's functionality.
 You can install these modules using tools like pip (Python package manager).
pip install module_name
 Common third-party modules include numpy, pandas, requests, and many others.
 Using modules in Python promotes code reusability and helps manage the complexity
of larger projects.
 By breaking down your code into smaller, modular components, you can work more
efficiently and collaborate effectively with other developers.
JISHNU M S 35
CREATING AND IMPORTING AND MODULES IN PYTHON
Creating and importing modules in Python is a fundamental concept for organizing your code and making it
more modular.
Step 1: Create a Module
1. Create a new file and give it a meaningful name with a .py extension. For example, let's create a module
named my_module.py.
2. Inside my_module.py, define functions, classes, or variables that you want to include in your module.
Here's an example:
JISHNU M S 36
def greet(name):
return f"Hello, {name}!"
def square(x):
return x ** 2
JISHNU M S 37
Step 2: Save the Module
Save the my_module.py file in the same directory as your main script or in a location where Python can
find it (e.g., a directory included in the sys.path list).
Step 3: Import and Use the Module
Now, you can import and use the module in another Python script.
1. Create a new Python script (e.g., main_script.py) in the same directory as the my_module.py module.
2. Import the module using the import statement:
import my_module
JISHNU M S 38
3. Use functions from the module in your script:
message = my_module.greet("Alice")
print(message) # Output: Hello,Alice!
result = my_module.square(5)
print(result) # Output: 25
JISHNU M S 39
Step 4: Run the Script
Run the main_script.py script using your Python interpreter.You should see the output corresponding to the
imported functions.
Note that you can also use the from ... import ... syntax to import specific functions or variables from the
module directly into your script's namespace:
from my_module import greet
message = greet("Bob")
print(message) # Output: Hello, Bob!
Keep in mind that the name of the module (e.g., my_module) acts as a namespace for the functions and variables
defined within it.This helps prevent naming conflicts between different modules.
CLASSES AND OBJECTS
A class is a blueprint or template for creating objects. It defines the attributes (data) and methods
(functions) that objects of that class will have. In Python, you define a class using the class
keyword followed by the class name and a colon. The attributes and methods are defined within the
class's body.
class person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(“Hello” + self.name)
In this example, we've defined a person class with attributes name and age, and a method greet()
Class
JISHNU M S 40
JISHNU M S 41
__INIT__ METHOD &THE SELF PARAMETER
 Constructor (__init__ method):
 The __init__ method is a special method called a constructor. It's used to initialize the
attributes of an object when it's created.
 The Self Method:
 The self-parameter refers to the current instance of the class and accesses the class
variables.
 We can use anything instead of self, but it must be the first parameter of any function
which belongs to the class.
 The self parameter refers to the object itself and is used to access its attributes and
methods.
JISHNU M S 42
Object:
An object is an instance of a class. It's a concrete entity that can hold data (attributes) and perform
actions (methods) as defined by the class. To create an object, you call the class as if it were a
function, which creates a new instance of that class.
In this case, person_obj is an object of the person class with the name attribute set to
"BCAA" and the age attribute set to 3.
person_obj = person("BCAA", 3)
JISHNU M S 43
Using Objects:
You can access the attributes and methods of an object using the dot (.) notation:
print(person_obj.name) # Output: BCAA
print(person_obj.age) # Output: 3
print(person_obj.greet()) # Output: Hello BCAA
Methods:
Methods are functions defined within a class. They operate on the attributes of the object and
can perform various actions. Methods often take the self parameter as the first parameter, which
refers to the instance of the class.
the describe() method provides a way to get a description of the dog.
JISHNU M S
44
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
def describe(self):
return f"{self.name} is {self.age} years old."
JISHNU M S 45
CLASS PROPERTIES
 class properties are attributes associated with a class that have special
behavior when accessed or modified.
 They provide a way to encapsulate and control the access to class-level
data.
 There are two main types of class properties:
 class variables and
 class methods.
JISHNU M S 46
ClassVariables:
 Class variables are shared among all instances of a class. They are defined within the
class scope but outside any methods.
 Class variables are accessible using the class name and can also be accessed through
instances of the class.
 They are often used to store data that is common to all instances of the class.
class MyClass:
class_variable = 0 # This is a class variable
def __init__(self, value):
self.instance_variable = value
obj1 = MyClass(10)
obj2 = MyClass(20)
print(obj1.class_variable) # Output: 0
print(obj2.class_variable) # Output: 0
JISHNU M S 47
Class Methods:
 Class methods are methods defined within a class that are bound to the class rather than
instances.
 They are defined using the @classmethod decorator and receive the class as their first
argument (often named cls by convention) or classmethod()
 Class methods are typically used to perform operations that are related to the class itself
rather than instances.
JISHNU M S 48
Class Methods:
class MyClass:
class_variable = 0
def __init__(self, value):
self.instance_variable = value
@classmethod
def modify_class_variable(cls, new_value):
cls.class_variable = new_value
obj1 = MyClass(10)
obj2 = MyClass(20)
obj1.modify_class_variable(5)
print(obj1.class_variable) # Output: 5
print(obj2.class_variable) # Output: 5
STATIC METHOD
 Static method is a method that belongs to a class but is not bound to instances
of that class.
 It's defined within the class, but it doesn't receive the class or instance as an
implicit first parameter (like instance methods or class methods do). Instead, it
behaves like a regular function, except it's namespaced within the class.
 static methods are typically used for utility functions that are related to the class
in some way but don't depend on or modify instance or class-specific data.
 They are defined using the @staticmethod decorator or staticmethod() and
do not require access to instance or class-specific information.
JISHNU M S 49
JISHNU M S 50
class MathUtils:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def subtract(x, y):
return x - y
result1 = MathUtils.add(5, 3)
result2 = MathUtils.subtract(10, 2)
print(result1) # Output: 8
print(result2) # Output: 8
In this example, the add and subtract methods are static
methods because they don't access any instance-
specific or class-specific data. They perform basic
arithmetic operations and are associated with the
MathUtils class, but they can be called using the class
name without creating instances of the class.
JISHNU M S 51
CONSTRUCTOR
 Constructor is a special method that gets automatically called when an object of a class is
created.
 It is a special member function which is used to initialize the attributes (properties) of the
object.
 The constructor method is named __init__ and is defined within the class.
JISHNU M S 52
CONSTRUCTOR
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating objects using the constructor
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Accessing object attributes
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
print(person2.name) # Output: Bob
print(person2.age) # Output: 25
 The __init__ method is the constructor for the
Person class.
 It takes two parameters, name and age, and
initializes the corresponding attributes of the
object being created using those values.
JISHNU M S 53
Key points about constructors in Python:
 The constructor method is named __init__.
 The first parameter of the constructor is conventionally named self, which refers to
the instance being created.
 The constructor is automatically called when an object of the class is created using
the class name followed by parentheses, like a function call.
 You can pass arguments to the constructor that will be used to initialize the object's
attributes.
 Inside the constructor, you can assign values to attributes using the self keyword.
 Constructors can have any number of parameters, not just self, and can perform any
necessary initialization.
JISHNU M S 54
METHOD OVERRIDING
 Method overriding in Python allows a subclass to provide a specific
implementation for a method that is already defined in its parent class.
 This enables you to customize the behavior of methods in the subclass
while maintaining the same method signature as the parent class.
 Method overriding is a key feature of polymorphism in object-oriented
programming.
How method overriding works
1. Method Signature:
 To override a method, the subclass method must have the same name and
parameters as the method in the parent class.
 The method in the subclass should be defined with the same method signature as the
one in the parent class.
2. Using the super() Function:
 Inside the overridden method of the subclass, you can use the super() function to
call the corresponding method of the parent class.
 This allows you to extend or modify the behavior of the parent class method
without completely replacing it.
JISHNU M S
55
56
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
animal = Animal()
dog = Dog()
cat = Cat()
print(animal.speak()) # Output: Animal speaks
print(dog.speak()) # Output: Woof
print(cat.speak()) # Output: Meow
the speak method is overridden in both the Dog and
Cat classes. Each subclass provides its own
implementation of the method, allowing them to
exhibit different behaviors while sharing the same
method name.
JISHNU M S
JISHNU M S 57
Key points about method overriding :
 Method overriding allows a subclass to provide a custom implementation for a
method defined in its parent class.
 The subclass method must have the same name and parameters as the method in the
parent class.
 The super() function is used to call the parent class method within the overridden
method.
 Overriding methods enables you to achieve polymorphism, where objects of different
subclasses can be treated uniformly through their common interface (method names).
58
class Animal():
def __init__(self, animal_type):
print('Animal Type:', animal_type)
class Mammal(Animal):
def __init__(self):
# call superclass
super().__init__('Mammal')
print('Mammals give birth directly')
dog = Mammal()
# Output: Animal Type: Mammal
# Mammals give birth directly
super()
JISHNU M S 59
class Parent():
def __init__(self, txt):
self.message=txt
def printmessage(self)
print(self.message)
Class Child(Parent):
def __init__(self, txt):
# call superclass
super().__init__(txt)
Obj=Child(“Hello, and Welcome!”)
Obj.printmessage()
super()
JISHNU M S 60
INHERITANCE
 Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows you to create a new class (subclass or derived class) based on an existing
class (superclass or base class).
 The new class inherits attributes and methods from the existing class, and you can
also add new attributes and methods or override existing ones in the subclass.
 Inheritance promotes code reuse, modularity, and the organization of code into a
hierarchy.
 You can create a subclass by defining a new class and specifying the superclass in
parentheses after the class name.
JISHNU M S 61
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.name) # Output: Buddy
print(dog.speak()) # Output: Woof
print(cat.name) # Output: Whiskers
print(cat.speak()) # Output: Meow
 Animal is the base class, and Dog and Cat are
subclasses that inherit from Animal.
 The subclasses override the speak method to
provide their own implementations, while still
inheriting the __init__ method and attribute from
the Animal class.
JISHNU M S 62
Key points about inheritance in Python:
 The base class is also known as the superclass or parent class.
 The derived class is also known as the subclass or child class.
 The subclass inherits attributes and methods from the superclass.
 You can add new attributes and methods to the subclass, or override existing ones.
 Inheritance supports the "is-a" relationship, where a subclass is a specific type of the
superclass.
 Python supports multiple inheritance, allowing a class to inherit from multiple parent
classes.
 The super() function is commonly used to call methods from the parent class within
overridden methods.
 Inheritance promotes code reuse, modularity, and the creation of hierarchical class
structures.
JISHNU M S 63
OPERATOR OVERLOADING
 Operator overloading refers to the ability to define custom behavior for standard
operators (+, -, *, /, etc.) when used with objects of user-defined classes.
 This allows you to make your objects behave more like built-in types, providing a
more intuitive and natural interface.
 To overload an operator for a user-defined class, you need to define special methods
with specific names that Python recognizes.
 These methods are also called "magic methods" or "dunder methods" (short for
"double underscore" methods).
 They have names that start and end with double underscores, such as __add__ for the
addition operator.
JISHNU M S 64
class opoverloading:
def __init__(self, x):
self.x = x
def __add__(self, other):
print(‘The value of Ob1 = ‘ ,self.x)
print(‘The value of Ob2 = ‘, other.x)
print(‘The addition of 2 objects is :’)
return((self.x+other.x)
# Create objects
Ob1 = opoverloading(20)
Ob2 = opoverloading(30)
# Use the overloaded + operator
Ob3 = Ob1 + Ob2
print(Ob3)
 As the above statement contains the + operator,
python automatically invokes the __add__ method.
 In the __add__ method, first parameter is the object
on which the method is invoked and the second
parameter is the other, which is used to distinguish
from self.
JISHNU M S 65
INTRODUCTION TO PIP
 Pip is the package installer for python.
 It's a command-line tool that allows you to install and manage python packages, which are
pre-written libraries or modules that provide specific functionality and can be easily reused
in your own projects.
 Python packages are typically published and shared on the python package index (pypi), a
repository of open-source python packages.
66
1. Installation:
If you're using a recent version of Python (Python 2.7.9+ or Python 3.4+), pip is usually already
installed. You can check if pip is installed by running pip --version in your terminal. If it's not
installed, you can install it by following the instructions on the official pip documentation.
2. Installing Packages:
To install a Python package using pip, you use the command pip install package_name. For
example, to install the popular requests package, you would run:
pip install requests
3. Listing Installed Packages:
You can list the packages installed in your Python environment using the command:
pip list
4. Uninstalling Packages:
To uninstall a package, you use the command pip uninstall package_name
pip uninstall requests
JISHNU M S
JISHNU M S 67
5. Specifying Package Versions:
You can specify a particular version of a package to install by including the version number
after the package name. For example:
pip install requests==2.25.1
6. Requirements Files:
You can create a requirements.txt file listing all the packages required for your project, along
with their versions. This is useful for sharing project dependencies with others or for
recreating the same environment later. You can generate a requirements file using:
pip freeze > requirements.txt
JISHNU M S 68
7. Installing from a Requirements File:
To install packages from a requirements file, you use the command:
pip install -r requirements.txt
8. Upgrading Packages:
To upgrade a package to the latest version, use the command:
pip install --upgrade package_name
9. Searching for Packages:
You can search for packages on PyPI using the command:
pip search search_term
JISHNU M S 69
10. Virtual Environments:
 It's recommended to use virtual environments to isolate your project's dependencies from
the system-wide Python installation.
 You can create a virtual environment using venv (for Python 3.3+) or virtualenv (for
earlier versions).
 pip is a powerful tool that simplifies the process of managing Python packages and their
dependencies, making it easier to work on projects that rely on various external libraries.
 It's a standard tool used by Python developers for creating consistent and reproducible
development environments.

More Related Content

PPTX
Functions in python, types of functions in python
SherinRappai
 
PPTX
Unit 2function in python.pptx
vishnupriyapm4
 
PPTX
Unit 2function in python.pptx
vishnupriyapm4
 
PPTX
Python for Data Science function third module ppt.pptx
bmit1
 
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PPTX
Functions_new.pptx
Yagna15
 
PPTX
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Functions in python, types of functions in python
SherinRappai
 
Unit 2function in python.pptx
vishnupriyapm4
 
Unit 2function in python.pptx
vishnupriyapm4
 
Python for Data Science function third module ppt.pptx
bmit1
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
Functions_new.pptx
Yagna15
 
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 

Similar to Unit 2 - Functions in python - Prof Jishnu M S (20)

PDF
Python functions
Prof. Dr. K. Adisesha
 
PPTX
Functions in python
colorsof
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PPTX
Python Details Functions Description.pptx
2442230910
 
PPTX
functions.pptx
KavithaChekuri3
 
PDF
Chapter Functions for grade 12 computer Science
KrithikaTM
 
PPT
functions _
SwatiHans10
 
PPTX
Decided to go to the 65 and the value of the number
harshoberoi2050
 
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
PDF
Functions2.pdf
prasnt1
 
PDF
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PDF
3-Python Functions.pdf in simple.........
mxdsnaps
 
PPSX
python Function
Ronak Rathi
 
PPTX
Python Functions.pptx
AnuragBharti27
 
PPTX
Chapter 2 Python Functions
11210208
 
PDF
ch-3 funtions - 1 class 12.pdf
zafar578075
 
PPTX
ESIT135: Unit 3 Topic: functions in python
SwapnaliGawali5
 
PPTX
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
PPTX
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
Python functions
Prof. Dr. K. Adisesha
 
Functions in python
colorsof
 
Functions in Python Programming Language
BeulahS2
 
Python Details Functions Description.pptx
2442230910
 
functions.pptx
KavithaChekuri3
 
Chapter Functions for grade 12 computer Science
KrithikaTM
 
functions _
SwatiHans10
 
Decided to go to the 65 and the value of the number
harshoberoi2050
 
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Functions2.pdf
prasnt1
 
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
3-Python Functions.pdf in simple.........
mxdsnaps
 
python Function
Ronak Rathi
 
Python Functions.pptx
AnuragBharti27
 
Chapter 2 Python Functions
11210208
 
ch-3 funtions - 1 class 12.pdf
zafar578075
 
ESIT135: Unit 3 Topic: functions in python
SwapnaliGawali5
 
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
Ad

Recently uploaded (20)

PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PPTX
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 
Understanding operators in c language.pptx
auteharshil95
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Landforms and landscapes data surprise preview
jpinnuck
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
Ad

Unit 2 - Functions in python - Prof Jishnu M S

  • 1. UNIT 2: FUNCTIONS IN PYTHON 1 Prof. JISHNU M S Assistant Professor Kristu Jayanti College(Autonomous), Bengaluru
  • 2. FUNCTION JISHNU M S 2  Function in Python is a reusable block of code that performs a single, specific and well defined task.  It allows you to encapsulate a set of instructions into a single unit, which you can then call by its name whenever you want to execute that set of instructions. WHY FUNCTION ?  Code Reusability  Modularity  Easy Debugging  Less Development Time
  • 3. HOW FUNCTION WORKS ? JISHNU M S 3
  • 4. SYNTAX OF FUNCTION DEFINITION JISHNU M S 4
  • 5. EXAMPLE OF FUNCTION DEFINITION JISHNU M S 5  In Python, you can define a function using the def keyword followed by the function name, a set of parentheses containing any parameters the function takes, and a colon.  The function body is indented and contains the code that defines what the function does.  You can also include a return statement to send a value back as the result of the function's execution.
  • 6. EXAMPLE 1 JISHNU M S 6 # function declaration def function(): print(“Hello world”) # calling function function() # function call
  • 7. EXAMPLE 2 JISHNU M S 7 def greet(name): return "Hello, " + name + "!" # Calling the function message = greet(“BCAA ") print(message) # Output: Hello, BCAA! The greet function takes a single parameter name and returns a greeting message
  • 8. FUNCTION PARAMETRES JISHNU M S 8 The name of the function while calling and the number of arguments must match with the function definition. If there is a mismatch in number of parameters passed and declared, then an error will be returned. If the data type of the parameter passed does not match with that of the function, then an error is generated.
  • 9. EXAMPLE 3 JISHNU M S 9 # function declaration def add(x,y): return x+y # main function m=10 n=4 print(add(m,n)) OR z=add(m,n) print(z)
  • 11. TYPES OF FUNCTIONS IN PYTHON JISHNU M S 11
  • 12. ANONYMOUS FUNCTIONS  Anonymous functions are known as "lambda" functions.  Lambda functions are not declared using def keyword. Instead lambda is used.  A lambda function is a small, inline function that doesn't have a formal name like a regular user-defined function.  Lambda functions are often used for short, simple operations that can be defined in a single line of code.  Any number of arguments can be supplied to lambda functions, but it must contain only a single expression. JISHNU M S 12
  • 13. ANONYMOUS FUNCTIONS  The syntax for creating a lambda function is as follows:  Here's a basic example of a lambda function that adds two numbers: JISHNU M S 13 lambda arguments : expression add = lambda x, y: x + y result = add(5, 3) print(result) # Output: 8
  • 14. JISHNU M S 14 ANONYMOUS FUNCTIONS 1. Lambda functions have no name 2. Lambda function cannot access variables other than those in their parameter list. 3. Lambda functions can take N number of arguments 4. Lambda functions does not have any return statement 5. It could have only a single expression
  • 15.  Lambda functions are typically used when you need a quick function for a short task, like passing a function as an argument to another function, working with higher-order functions like map(), filter(), or sorted(), or creating simple key functions for sorting.  Here's an example of using a lambda function with the sorted() function: points = [(3, 5), (1, 9), (8, 2)] sorted_points = sorted(points, key=lambda point: point[1]) #Sorting by the second element of each tuple print(sorted_points) # Output: [(8, 2), (3, 5), (1, 9)]  Lambda functions can be useful in situations where defining a full named function might be unnecessary due to the function's simplicity.  However, for more complex or larger functions, it's generally better to use regular user- defined functions for clarity and maintainability. JISHNU M S 15
  • 16. JISHNU M S 16 RECURSIVE FUNCTIONS Recursive function is a function that calls itself as part of its execution. Recursive functions are used to solve problems that can be broken down into smaller instances of the same problem. Each recursive call works on a smaller piece of the problem until it reaches a base case where a direct solution can be obtained without further recursion. Recursive functions can be a powerful tool for solving certain types of problems, but they should be designed carefully to avoid infinite recursion and excessive function calls.
  • 17. 17 RECURSIVE FUNCTION EXAMPLE  Suppose we want to calculate the factorial value of an integer [n! = n * (n-1)!] JISHNU M S def factorial(n): if n == 0: return 1 else return n * factorial (n-1) print(factorial(5)) # output will be 120
  • 18. calculating the factorial of a non-negative integer n: def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) result = factorial(5) # 5! = 5 * 4 * 3 * 2 * 1 = 120 print(result) # Output: 120 The factorial function calls itself with a smaller value of n until it reaches the base case where n is 0. This base case returns 1, and the function then starts "unwinding" the recursive calls, multiplying each value of n until the original call is complete.  When creating recursive functions, it's important to define the base case(s) that will terminate the recursion and prevent infinite loops.  Without a proper base case, the function would keep calling itself indefinitely and eventually lead to a "RecursionError" due to exceeding the maximum recursion depth. JISHNU M S 18
  • 19. Calculating the Fibonacci sequence: def fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) result = fibonacci(6) # Fibonacci sequence: 0, 1, 1, 2, 3, 5, ... print(result) # Output: 8 The fibonacci function calculates the nth number in the Fibonacci sequence by recursively summing the previous two numbers.  Recursive functions can be elegant solutions for certain problems, but they can also be less efficient than iterative approaches in terms of memory and performance.  When using recursion, it's important to understand the trade-offs and choose the appropriate approach based on the problem's requirements. JISHNU M S 19
  • 20. JISHNU M S 20 USER-DEFINED FUNCTIONS IN PYTHON  User-defined functions in Python are functions that you create yourself to perform specific tasks according to your needs.  They allow you to encapsulate a block of code into a reusable unit, making your code more organized and modular.  To define a user-defined function in Python, you use the def keyword followed by the function name, a set of parentheses containing any parameters the function takes (if any), and a colon (:).  The function body is indented and contains the code that defines what the function does.  You can also include a return statement to send a value back as the result of the function's execution.
  • 21. Here's the basic syntax for defining a user-defined function: Here's an example of a simple user-defined function: JISHNU M S 21 def function_name(parameters): # Function body # Code to perform the task return result # Optional def add_numbers(a, b): return a + b result = add_numbers(5, 3) print(result) # Output: 8
  • 22. JISHNU M S 22 FUNCTIONS ARGUMENTS  You can call a function by using this types of formal parameters
  • 23. JISHNU M S 23 1. REQUIRED ARGUMENTS  Arguments must be passed on to a function in correct order.  The number of arguments passed to a function must match with the number of arguments specified in the function definition def prd ( a , b): prd = a * b return prd product = prd ( 12, 2) print ( product ) # output will be 24
  • 24. JISHNU M S 24 2. KEYWORD ARGUMENTS  A keyword argument helps to identify arguments by specifying the name of the parameter.  The order of the keyword argument is not important.  The keyword arguments passed must match with one of the arguments of the accepting function.  It makes the program code less complex and easy to understand
  • 25. JISHNU M S 25 2. KEYWORD ARGUMENTS def student ( name, course, fees): print(“Name: “, name) print(“Course: “, course) print(“Fees: “, fees) n = “Ashok” c = “BCA” f = “30000” Student ( fees=f, name=n, course=c) # output will be Name: Ashok Course: BCA Fees : 30000
  • 26. JISHNU M S 26 3. DEFAULT ARGUMENTS  It allow to specify a value for a parameter  This allow to call a function with less number of arguments defined.  Any number of default arguments can be defined.  Non default argument cannot be followed by the default arguments def student ( name, course = “BCA): print(“Name: “, name) print(“Course: “, course) Student ( name= “Ashok”) # output will be Name: Ashok Course: BCA
  • 27. JISHNU M S 27 4. VARIABLE - LENGTH ARGUMENTS  In cases where it is not known in prior how many arguments will be passed to a function , python allows to make function call with arbitrary number of arguments  An asterisk (* ) symbol is used before the parameter name. def vlen ( course, sem, *sub_mark): print(“Course: “, course) print(“Sem: “, sem) for p in sub_mark: print(“sub_mark: “, sub_mark) vlen (“BCA”, “fifth”, 100, 99, 90) # output will be Course: BCA Sem: fifth Sub_mark: 100 Sub_mark: 99 Sub_mark: 90
  • 28. 28 INTRODUCTION TO MODULES  A module is a .py extension file which has the definitions of all the functions, classes, and variables that can be used in other Python programs.  Modules provide a way to organize your code and make it more modular, reusable, and maintainable.  In simple terms we can consider a module to be same as the code library or file that contains a certain function that can be included in the application.  The program which want to use functions & variables defined in the module will use import keyword to link or import the module or the .py file JISHNU M S
  • 29. 29 INTRODUCTION TO MODULES  Python has a rich collection of built-in modules, and you can also create your own custom modules to encapsulate related functionality.  If we need to organize the code logically one of the best method is to use modules. JISHNU M S
  • 30. JISHNU M S 30 Introduction to working with modules in Python: 1. Built-in Modules: Python comes with a set of built-in modules that provide various functionalities. Some common examples include: a. math: Provides mathematical functions and constants. b. random: Generates random numbers. c. datetime: Manipulates dates and times. d. os: Interacts with the operating system, like reading directories and files. e. sys: Provides access to system-specific parameters and functions.
  • 31. JISHNU M S 31 2. Importing Modules: To use functions, classes, or variables from a module, you need to import the module into your code. The import statement is used for this purpose. For example: import math print(math.sqrt(16)) # Output: 4.0 You can also use the from keyword to import specific items from a module: from math import sqrt print(sqrt(16)) # Output: 4.0
  • 32. JISHNU M S 32 3. Creating Custom Modules: You can create your own modules by creating a .py file and placing your Python code inside it. For example, if you create a file named my_module.py with the following content: Module 1: demo.py Module 2 def disp (name): print(“Hello”, +name) import demo demo.disp(“BCAA”)
  • 33. JISHNU M S 33 4. Package:  A package is a collection of related modules organized in a directory hierarchy. It includes a special __init__.py  __init__.py file that makes Python treat the directory as a package.  Packages allow you to organize related modules into a coherent structure.
  • 34. JISHNU M S 34 5. Third-party Modules:  Python has a vast ecosystem of third-party modules that you can install and use to extend your code's functionality.  You can install these modules using tools like pip (Python package manager). pip install module_name  Common third-party modules include numpy, pandas, requests, and many others.  Using modules in Python promotes code reusability and helps manage the complexity of larger projects.  By breaking down your code into smaller, modular components, you can work more efficiently and collaborate effectively with other developers.
  • 35. JISHNU M S 35 CREATING AND IMPORTING AND MODULES IN PYTHON Creating and importing modules in Python is a fundamental concept for organizing your code and making it more modular. Step 1: Create a Module 1. Create a new file and give it a meaningful name with a .py extension. For example, let's create a module named my_module.py. 2. Inside my_module.py, define functions, classes, or variables that you want to include in your module. Here's an example:
  • 36. JISHNU M S 36 def greet(name): return f"Hello, {name}!" def square(x): return x ** 2
  • 37. JISHNU M S 37 Step 2: Save the Module Save the my_module.py file in the same directory as your main script or in a location where Python can find it (e.g., a directory included in the sys.path list). Step 3: Import and Use the Module Now, you can import and use the module in another Python script. 1. Create a new Python script (e.g., main_script.py) in the same directory as the my_module.py module. 2. Import the module using the import statement: import my_module
  • 38. JISHNU M S 38 3. Use functions from the module in your script: message = my_module.greet("Alice") print(message) # Output: Hello,Alice! result = my_module.square(5) print(result) # Output: 25
  • 39. JISHNU M S 39 Step 4: Run the Script Run the main_script.py script using your Python interpreter.You should see the output corresponding to the imported functions. Note that you can also use the from ... import ... syntax to import specific functions or variables from the module directly into your script's namespace: from my_module import greet message = greet("Bob") print(message) # Output: Hello, Bob! Keep in mind that the name of the module (e.g., my_module) acts as a namespace for the functions and variables defined within it.This helps prevent naming conflicts between different modules.
  • 40. CLASSES AND OBJECTS A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that objects of that class will have. In Python, you define a class using the class keyword followed by the class name and a colon. The attributes and methods are defined within the class's body. class person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(“Hello” + self.name) In this example, we've defined a person class with attributes name and age, and a method greet() Class JISHNU M S 40
  • 41. JISHNU M S 41 __INIT__ METHOD &THE SELF PARAMETER  Constructor (__init__ method):  The __init__ method is a special method called a constructor. It's used to initialize the attributes of an object when it's created.  The Self Method:  The self-parameter refers to the current instance of the class and accesses the class variables.  We can use anything instead of self, but it must be the first parameter of any function which belongs to the class.  The self parameter refers to the object itself and is used to access its attributes and methods.
  • 42. JISHNU M S 42 Object: An object is an instance of a class. It's a concrete entity that can hold data (attributes) and perform actions (methods) as defined by the class. To create an object, you call the class as if it were a function, which creates a new instance of that class. In this case, person_obj is an object of the person class with the name attribute set to "BCAA" and the age attribute set to 3. person_obj = person("BCAA", 3)
  • 43. JISHNU M S 43 Using Objects: You can access the attributes and methods of an object using the dot (.) notation: print(person_obj.name) # Output: BCAA print(person_obj.age) # Output: 3 print(person_obj.greet()) # Output: Hello BCAA
  • 44. Methods: Methods are functions defined within a class. They operate on the attributes of the object and can perform various actions. Methods often take the self parameter as the first parameter, which refers to the instance of the class. the describe() method provides a way to get a description of the dog. JISHNU M S 44 class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): return "Woof!" def describe(self): return f"{self.name} is {self.age} years old."
  • 45. JISHNU M S 45 CLASS PROPERTIES  class properties are attributes associated with a class that have special behavior when accessed or modified.  They provide a way to encapsulate and control the access to class-level data.  There are two main types of class properties:  class variables and  class methods.
  • 46. JISHNU M S 46 ClassVariables:  Class variables are shared among all instances of a class. They are defined within the class scope but outside any methods.  Class variables are accessible using the class name and can also be accessed through instances of the class.  They are often used to store data that is common to all instances of the class. class MyClass: class_variable = 0 # This is a class variable def __init__(self, value): self.instance_variable = value obj1 = MyClass(10) obj2 = MyClass(20) print(obj1.class_variable) # Output: 0 print(obj2.class_variable) # Output: 0
  • 47. JISHNU M S 47 Class Methods:  Class methods are methods defined within a class that are bound to the class rather than instances.  They are defined using the @classmethod decorator and receive the class as their first argument (often named cls by convention) or classmethod()  Class methods are typically used to perform operations that are related to the class itself rather than instances.
  • 48. JISHNU M S 48 Class Methods: class MyClass: class_variable = 0 def __init__(self, value): self.instance_variable = value @classmethod def modify_class_variable(cls, new_value): cls.class_variable = new_value obj1 = MyClass(10) obj2 = MyClass(20) obj1.modify_class_variable(5) print(obj1.class_variable) # Output: 5 print(obj2.class_variable) # Output: 5
  • 49. STATIC METHOD  Static method is a method that belongs to a class but is not bound to instances of that class.  It's defined within the class, but it doesn't receive the class or instance as an implicit first parameter (like instance methods or class methods do). Instead, it behaves like a regular function, except it's namespaced within the class.  static methods are typically used for utility functions that are related to the class in some way but don't depend on or modify instance or class-specific data.  They are defined using the @staticmethod decorator or staticmethod() and do not require access to instance or class-specific information. JISHNU M S 49
  • 50. JISHNU M S 50 class MathUtils: @staticmethod def add(x, y): return x + y @staticmethod def subtract(x, y): return x - y result1 = MathUtils.add(5, 3) result2 = MathUtils.subtract(10, 2) print(result1) # Output: 8 print(result2) # Output: 8 In this example, the add and subtract methods are static methods because they don't access any instance- specific or class-specific data. They perform basic arithmetic operations and are associated with the MathUtils class, but they can be called using the class name without creating instances of the class.
  • 51. JISHNU M S 51 CONSTRUCTOR  Constructor is a special method that gets automatically called when an object of a class is created.  It is a special member function which is used to initialize the attributes (properties) of the object.  The constructor method is named __init__ and is defined within the class.
  • 52. JISHNU M S 52 CONSTRUCTOR class Person: def __init__(self, name, age): self.name = name self.age = age # Creating objects using the constructor person1 = Person("Alice", 30) person2 = Person("Bob", 25) # Accessing object attributes print(person1.name) # Output: Alice print(person1.age) # Output: 30 print(person2.name) # Output: Bob print(person2.age) # Output: 25  The __init__ method is the constructor for the Person class.  It takes two parameters, name and age, and initializes the corresponding attributes of the object being created using those values.
  • 53. JISHNU M S 53 Key points about constructors in Python:  The constructor method is named __init__.  The first parameter of the constructor is conventionally named self, which refers to the instance being created.  The constructor is automatically called when an object of the class is created using the class name followed by parentheses, like a function call.  You can pass arguments to the constructor that will be used to initialize the object's attributes.  Inside the constructor, you can assign values to attributes using the self keyword.  Constructors can have any number of parameters, not just self, and can perform any necessary initialization.
  • 54. JISHNU M S 54 METHOD OVERRIDING  Method overriding in Python allows a subclass to provide a specific implementation for a method that is already defined in its parent class.  This enables you to customize the behavior of methods in the subclass while maintaining the same method signature as the parent class.  Method overriding is a key feature of polymorphism in object-oriented programming.
  • 55. How method overriding works 1. Method Signature:  To override a method, the subclass method must have the same name and parameters as the method in the parent class.  The method in the subclass should be defined with the same method signature as the one in the parent class. 2. Using the super() Function:  Inside the overridden method of the subclass, you can use the super() function to call the corresponding method of the parent class.  This allows you to extend or modify the behavior of the parent class method without completely replacing it. JISHNU M S 55
  • 56. 56 class Animal: def speak(self): return "Animal speaks" class Dog(Animal): def speak(self): return "Woof" class Cat(Animal): def speak(self): return "Meow" animal = Animal() dog = Dog() cat = Cat() print(animal.speak()) # Output: Animal speaks print(dog.speak()) # Output: Woof print(cat.speak()) # Output: Meow the speak method is overridden in both the Dog and Cat classes. Each subclass provides its own implementation of the method, allowing them to exhibit different behaviors while sharing the same method name. JISHNU M S
  • 57. JISHNU M S 57 Key points about method overriding :  Method overriding allows a subclass to provide a custom implementation for a method defined in its parent class.  The subclass method must have the same name and parameters as the method in the parent class.  The super() function is used to call the parent class method within the overridden method.  Overriding methods enables you to achieve polymorphism, where objects of different subclasses can be treated uniformly through their common interface (method names).
  • 58. 58 class Animal(): def __init__(self, animal_type): print('Animal Type:', animal_type) class Mammal(Animal): def __init__(self): # call superclass super().__init__('Mammal') print('Mammals give birth directly') dog = Mammal() # Output: Animal Type: Mammal # Mammals give birth directly super()
  • 59. JISHNU M S 59 class Parent(): def __init__(self, txt): self.message=txt def printmessage(self) print(self.message) Class Child(Parent): def __init__(self, txt): # call superclass super().__init__(txt) Obj=Child(“Hello, and Welcome!”) Obj.printmessage() super()
  • 60. JISHNU M S 60 INHERITANCE  Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create a new class (subclass or derived class) based on an existing class (superclass or base class).  The new class inherits attributes and methods from the existing class, and you can also add new attributes and methods or override existing ones in the subclass.  Inheritance promotes code reuse, modularity, and the organization of code into a hierarchy.  You can create a subclass by defining a new class and specifying the superclass in parentheses after the class name.
  • 61. JISHNU M S 61 class Animal: def __init__(self, name): self.name = name def speak(self): return "Animal speaks" class Dog(Animal): def speak(self): return "Woof" class Cat(Animal): def speak(self): return "Meow" dog = Dog("Buddy") cat = Cat("Whiskers") print(dog.name) # Output: Buddy print(dog.speak()) # Output: Woof print(cat.name) # Output: Whiskers print(cat.speak()) # Output: Meow  Animal is the base class, and Dog and Cat are subclasses that inherit from Animal.  The subclasses override the speak method to provide their own implementations, while still inheriting the __init__ method and attribute from the Animal class.
  • 62. JISHNU M S 62 Key points about inheritance in Python:  The base class is also known as the superclass or parent class.  The derived class is also known as the subclass or child class.  The subclass inherits attributes and methods from the superclass.  You can add new attributes and methods to the subclass, or override existing ones.  Inheritance supports the "is-a" relationship, where a subclass is a specific type of the superclass.  Python supports multiple inheritance, allowing a class to inherit from multiple parent classes.  The super() function is commonly used to call methods from the parent class within overridden methods.  Inheritance promotes code reuse, modularity, and the creation of hierarchical class structures.
  • 63. JISHNU M S 63 OPERATOR OVERLOADING  Operator overloading refers to the ability to define custom behavior for standard operators (+, -, *, /, etc.) when used with objects of user-defined classes.  This allows you to make your objects behave more like built-in types, providing a more intuitive and natural interface.  To overload an operator for a user-defined class, you need to define special methods with specific names that Python recognizes.  These methods are also called "magic methods" or "dunder methods" (short for "double underscore" methods).  They have names that start and end with double underscores, such as __add__ for the addition operator.
  • 64. JISHNU M S 64 class opoverloading: def __init__(self, x): self.x = x def __add__(self, other): print(‘The value of Ob1 = ‘ ,self.x) print(‘The value of Ob2 = ‘, other.x) print(‘The addition of 2 objects is :’) return((self.x+other.x) # Create objects Ob1 = opoverloading(20) Ob2 = opoverloading(30) # Use the overloaded + operator Ob3 = Ob1 + Ob2 print(Ob3)  As the above statement contains the + operator, python automatically invokes the __add__ method.  In the __add__ method, first parameter is the object on which the method is invoked and the second parameter is the other, which is used to distinguish from self.
  • 65. JISHNU M S 65 INTRODUCTION TO PIP  Pip is the package installer for python.  It's a command-line tool that allows you to install and manage python packages, which are pre-written libraries or modules that provide specific functionality and can be easily reused in your own projects.  Python packages are typically published and shared on the python package index (pypi), a repository of open-source python packages.
  • 66. 66 1. Installation: If you're using a recent version of Python (Python 2.7.9+ or Python 3.4+), pip is usually already installed. You can check if pip is installed by running pip --version in your terminal. If it's not installed, you can install it by following the instructions on the official pip documentation. 2. Installing Packages: To install a Python package using pip, you use the command pip install package_name. For example, to install the popular requests package, you would run: pip install requests 3. Listing Installed Packages: You can list the packages installed in your Python environment using the command: pip list 4. Uninstalling Packages: To uninstall a package, you use the command pip uninstall package_name pip uninstall requests JISHNU M S
  • 67. JISHNU M S 67 5. Specifying Package Versions: You can specify a particular version of a package to install by including the version number after the package name. For example: pip install requests==2.25.1 6. Requirements Files: You can create a requirements.txt file listing all the packages required for your project, along with their versions. This is useful for sharing project dependencies with others or for recreating the same environment later. You can generate a requirements file using: pip freeze > requirements.txt
  • 68. JISHNU M S 68 7. Installing from a Requirements File: To install packages from a requirements file, you use the command: pip install -r requirements.txt 8. Upgrading Packages: To upgrade a package to the latest version, use the command: pip install --upgrade package_name 9. Searching for Packages: You can search for packages on PyPI using the command: pip search search_term
  • 69. JISHNU M S 69 10. Virtual Environments:  It's recommended to use virtual environments to isolate your project's dependencies from the system-wide Python installation.  You can create a virtual environment using venv (for Python 3.3+) or virtualenv (for earlier versions).  pip is a powerful tool that simplifies the process of managing Python packages and their dependencies, making it easier to work on projects that rely on various external libraries.  It's a standard tool used by Python developers for creating consistent and reproducible development environments.