SlideShare a Scribd company logo
1 of 46
UNIT 2: FUNCTIONS IN PYTHON
VISHNU PRIYA P M 1
FUNCTION
Function in Python is a reusable block of code that performs a specific 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. Functions provide modularity, reusability, and
organization to your code.
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.
def greet(name):
return "Hello, " + name + "!"
# Calling the function
message = greet("Alice")
print(message) # Output: Hello,
Alice! the greet function takes a single parameter name and returns a greeting
VISHNU PRIYA P M 2
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.
VISHNU PRIYA P M 3
Here's the basic syntax for defining a user-defined function:
def function_name(parameters):
# Function body
# Code to perform the task
return result # Optional
Here's an example of a simple user-defined function:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
VISHNU PRIYA P M 4
the add_numbers function takes two parameters a and b, and returns their sum.
User-defined functions can have multiple parameters, and those parameters can have default
values. You can call a user-defined function by providing the required arguments in the same order
as the function definition, or by using keyword arguments to specify which parameter you're
providing a value for.
Here's an example with default parameters and keyword arguments:
def greet(name, message="Hello"):
return f"{message}, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
print(greet("Bob", message="Hi")) # Output: Hi, Bob!
User-defined functions can be as simple or as complex as you need them to be, and they greatly enhance the
reusability and readability of your code.
#formatted string is constructed using an f-string.
VISHNU PRIYA P M 5
ANONYMOUS FUNCTIONS
Anonymous functions are known as "lambda" functions. 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.
The syntax for creating a lambda function is as follows:
lambda arguments: expression
Here's a basic example of a lambda function that adds two numbers:
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
VISHNU PRIYA P M 6
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.
VISHNU PRIYA P M 7
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.
VISHNU PRIYA P M 8
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.
VISHNU PRIYA P M 9
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.
VISHNU PRIYA P M 10
INTRODUCTION TO MODULES
A module is a file containing Python definitions, 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. Python has a rich collection of built-in modules, and you can also
create your own custom modules to encapsulate related functionality.
VISHNU PRIYA P M 11
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.
VISHNU PRIYA P M 12
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
VISHNU PRIYA P M 13
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:
def greet(name):
return f"Hello, {name}!"
You can then use this module in another script:
import my_module
message = my_module.greet("Alice")
print(message) # Output: Hello, Alice!
VISHNU PRIYA P M 14
4. Package: A package is a collection of related modules organized in a directory hierarchy. It
includes a special __init__.py file that makes Python treat the directory as a package. Packages
allow you to organize related modules into a coherent structure.
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.
VISHNU PRIYA P M 15
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:
VISHNU PRIYA P M 16
def greet(name):
return f"Hello, {name}!"
def square(x):
return x ** 2
VISHNU PRIYA P M 17
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
VISHNU PRIYA P M 18
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
VISHNU PRIYA P M 19
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.
VISHNU PRIYA P M 20
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 Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
In this example, we've defined a Dog class with attributes name and age, and a method bark()
Class
VISHNU PRIYA P M 21
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.
my_dog = Dog("Buddy", 3)
In this case, my_dog is an object of the Dog class with the name attribute set to "Buddy" and the age
attribute set to 3.
VISHNU PRIYA P M 22
Using Objects:
You can access the attributes and methods of an object using the dot (.) notation:
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
print(my_dog.bark()) # Output: Woof!
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 parameter refers to the object itself and is used to access its
attributes and methods.
VISHNU PRIYA P M 23
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.
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."
the describe() method provides a way to get a description of the
dog.
VISHNU PRIYA P M 24
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.
VISHNU PRIYA P M 25
Class Variables:
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
VISHNU PRIYA P M 26
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). Class
methods are typically used to perform operations that are related to the class
itself rather than instances. 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
VISHNU PRIYA P M 27
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 and do not require access to
instance or class-specific information.
VISHNU PRIYA P M 28
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.
VISHNU PRIYA P M 29
CONSTRUCTOR
Constructor is a special method that gets automatically called when an object of a class is created.
It's used to initialize the attributes (properties) of the object. The constructor method is named
__init__ and is defined within the class.
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.
VISHNU PRIYA P M 30
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.
VISHNU PRIYA P M 31
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.
VISHNU PRIYA P M 32
How method overriding works
• 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.
• 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.
VISHNU PRIYA P M 33
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.
VISHNU PRIYA P M 34
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).
 Overriding methods in Python is a way to implement the "Liskov Substitution
Principle," which is one of the SOLID principles of object-oriented design.
VISHNU PRIYA P M 35
VISHNU PRIYA P M 36
class Animal(object):
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()
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.
VISHNU PRIYA P M 37
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.
VISHNU PRIYA P M 38
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.
VISHNU PRIYA P M 39
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.
VISHNU PRIYA P M 40
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y)
else:
raise TypeError("Unsupported operand type")
def __str__(self):
return f"({self.x}, {self.y})"
# Create points
p1 = Point(1, 2)
p2 = Point(3, 4)
# Use the overloaded + operator
result = p1 + p2
print(result) # Output: (4, 6)
we've overloaded the + operator by defining the __add__
method in the Point class. When the + operator is used
between two Point objects, the __add__ method is called,
and we perform addition element-wise on the x and y
coordinates.
VISHNU PRIYA P M 41
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.
VISHNU PRIYA P M 42
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
VISHNU PRIYA P M 43
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
VISHNU PRIYA P M 44
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
VISHNU PRIYA P M 45
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.
VISHNU PRIYA P M 46

More Related Content

Similar to Unit 2function in python.pptx

Similar to Unit 2function in python.pptx (20)

Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Chapter - 4.pptx
Chapter - 4.pptxChapter - 4.pptx
Chapter - 4.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdf
 

More from vishnupriyapm4

introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHPvishnupriyapm4
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxvishnupriyapm4
 
Introduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptxIntroduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptxvishnupriyapm4
 
OPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptxOPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptxvishnupriyapm4
 
Project Planning and Management.pptx
Project Planning and Management.pptxProject Planning and Management.pptx
Project Planning and Management.pptxvishnupriyapm4
 
Software_Process_Model for class.ppt
Software_Process_Model for class.pptSoftware_Process_Model for class.ppt
Software_Process_Model for class.pptvishnupriyapm4
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functionsvishnupriyapm4
 
Session and cookies in php
Session and cookies in phpSession and cookies in php
Session and cookies in phpvishnupriyapm4
 
Break and continue in C
Break and continue in C Break and continue in C
Break and continue in C vishnupriyapm4
 

More from vishnupriyapm4 (18)

introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHP
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptx
 
pccf unit 1 _VP.pptx
pccf unit 1 _VP.pptxpccf unit 1 _VP.pptx
pccf unit 1 _VP.pptx
 
Introduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptxIntroduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptx
 
Entity_DBMS.pptx
Entity_DBMS.pptxEntity_DBMS.pptx
Entity_DBMS.pptx
 
Unit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptxUnit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptx
 
Unit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptxUnit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptx
 
OPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptxOPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptx
 
Open Source VP.pptx
Open Source VP.pptxOpen Source VP.pptx
Open Source VP.pptx
 
Project Planning and Management.pptx
Project Planning and Management.pptxProject Planning and Management.pptx
Project Planning and Management.pptx
 
Software_Process_Model for class.ppt
Software_Process_Model for class.pptSoftware_Process_Model for class.ppt
Software_Process_Model for class.ppt
 
2.java intro.pptx
2.java intro.pptx2.java intro.pptx
2.java intro.pptx
 
features of JAVA.pptx
features of JAVA.pptxfeatures of JAVA.pptx
features of JAVA.pptx
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functions
 
Session and cookies in php
Session and cookies in phpSession and cookies in php
Session and cookies in php
 
constant in C
constant in Cconstant in C
constant in C
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Break and continue in C
Break and continue in C Break and continue in C
Break and continue in C
 

Recently uploaded

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

Unit 2function in python.pptx

  • 1. UNIT 2: FUNCTIONS IN PYTHON VISHNU PRIYA P M 1
  • 2. FUNCTION Function in Python is a reusable block of code that performs a specific 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. Functions provide modularity, reusability, and organization to your code. 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. def greet(name): return "Hello, " + name + "!" # Calling the function message = greet("Alice") print(message) # Output: Hello, Alice! the greet function takes a single parameter name and returns a greeting VISHNU PRIYA P M 2
  • 3. 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. VISHNU PRIYA P M 3
  • 4. Here's the basic syntax for defining a user-defined function: def function_name(parameters): # Function body # Code to perform the task return result # Optional Here's an example of a simple user-defined function: def add_numbers(a, b): return a + b result = add_numbers(5, 3) print(result) # Output: 8 VISHNU PRIYA P M 4
  • 5. the add_numbers function takes two parameters a and b, and returns their sum. User-defined functions can have multiple parameters, and those parameters can have default values. You can call a user-defined function by providing the required arguments in the same order as the function definition, or by using keyword arguments to specify which parameter you're providing a value for. Here's an example with default parameters and keyword arguments: def greet(name, message="Hello"): return f"{message}, {name}!" print(greet("Alice")) # Output: Hello, Alice! print(greet("Bob", message="Hi")) # Output: Hi, Bob! User-defined functions can be as simple or as complex as you need them to be, and they greatly enhance the reusability and readability of your code. #formatted string is constructed using an f-string. VISHNU PRIYA P M 5
  • 6. ANONYMOUS FUNCTIONS Anonymous functions are known as "lambda" functions. 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. The syntax for creating a lambda function is as follows: lambda arguments: expression Here's a basic example of a lambda function that adds two numbers: add = lambda x, y: x + y result = add(5, 3) print(result) # Output: 8 VISHNU PRIYA P M 6
  • 7. 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. VISHNU PRIYA P M 7
  • 8. 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. VISHNU PRIYA P M 8
  • 9. 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. VISHNU PRIYA P M 9
  • 10. 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. VISHNU PRIYA P M 10
  • 11. INTRODUCTION TO MODULES A module is a file containing Python definitions, 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. Python has a rich collection of built-in modules, and you can also create your own custom modules to encapsulate related functionality. VISHNU PRIYA P M 11
  • 12. 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. VISHNU PRIYA P M 12
  • 13. 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 VISHNU PRIYA P M 13
  • 14. 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: def greet(name): return f"Hello, {name}!" You can then use this module in another script: import my_module message = my_module.greet("Alice") print(message) # Output: Hello, Alice! VISHNU PRIYA P M 14
  • 15. 4. Package: A package is a collection of related modules organized in a directory hierarchy. It includes a special __init__.py file that makes Python treat the directory as a package. Packages allow you to organize related modules into a coherent structure. 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. VISHNU PRIYA P M 15
  • 16. 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: VISHNU PRIYA P M 16
  • 17. def greet(name): return f"Hello, {name}!" def square(x): return x ** 2 VISHNU PRIYA P M 17
  • 18. 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 VISHNU PRIYA P M 18
  • 19. 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 VISHNU PRIYA P M 19
  • 20. 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. VISHNU PRIYA P M 20
  • 21. 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 Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): return "Woof!" In this example, we've defined a Dog class with attributes name and age, and a method bark() Class VISHNU PRIYA P M 21
  • 22. 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. my_dog = Dog("Buddy", 3) In this case, my_dog is an object of the Dog class with the name attribute set to "Buddy" and the age attribute set to 3. VISHNU PRIYA P M 22
  • 23. Using Objects: You can access the attributes and methods of an object using the dot (.) notation: print(my_dog.name) # Output: Buddy print(my_dog.age) # Output: 3 print(my_dog.bark()) # Output: Woof! 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 parameter refers to the object itself and is used to access its attributes and methods. VISHNU PRIYA P M 23
  • 24. 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. 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." the describe() method provides a way to get a description of the dog. VISHNU PRIYA P M 24
  • 25. 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. VISHNU PRIYA P M 25
  • 26. Class Variables: 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 VISHNU PRIYA P M 26
  • 27. 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). Class methods are typically used to perform operations that are related to the class itself rather than instances. 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 VISHNU PRIYA P M 27
  • 28. 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 and do not require access to instance or class-specific information. VISHNU PRIYA P M 28
  • 29. 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. VISHNU PRIYA P M 29
  • 30. CONSTRUCTOR Constructor is a special method that gets automatically called when an object of a class is created. It's used to initialize the attributes (properties) of the object. The constructor method is named __init__ and is defined within the class. 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. VISHNU PRIYA P M 30
  • 31. 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. VISHNU PRIYA P M 31
  • 32. 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. VISHNU PRIYA P M 32
  • 33. How method overriding works • 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. • 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. VISHNU PRIYA P M 33
  • 34. 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. VISHNU PRIYA P M 34
  • 35. 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).  Overriding methods in Python is a way to implement the "Liskov Substitution Principle," which is one of the SOLID principles of object-oriented design. VISHNU PRIYA P M 35
  • 36. VISHNU PRIYA P M 36 class Animal(object): 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()
  • 37. 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. VISHNU PRIYA P M 37
  • 38. 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. VISHNU PRIYA P M 38
  • 39. 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. VISHNU PRIYA P M 39
  • 40. 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. VISHNU PRIYA P M 40
  • 41. class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Point): return Point(self.x + other.x, self.y + other.y) else: raise TypeError("Unsupported operand type") def __str__(self): return f"({self.x}, {self.y})" # Create points p1 = Point(1, 2) p2 = Point(3, 4) # Use the overloaded + operator result = p1 + p2 print(result) # Output: (4, 6) we've overloaded the + operator by defining the __add__ method in the Point class. When the + operator is used between two Point objects, the __add__ method is called, and we perform addition element-wise on the x and y coordinates. VISHNU PRIYA P M 41
  • 42. 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. VISHNU PRIYA P M 42
  • 43. 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 VISHNU PRIYA P M 43
  • 44. 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 VISHNU PRIYA P M 44
  • 45. 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 VISHNU PRIYA P M 45
  • 46. 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. VISHNU PRIYA P M 46