SlideShare a Scribd company logo
UNIT 2: FUNCTIONS IN PYTHON
SHERIN RAPPAI 1
FUNCTION
SHERIN RAPPAI 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 ?
SHERIN RAPPAI 3
SYNTAX OF FUNCTION DEFINITION
SHERIN RAPPAI 4
EXAMPLE OF FUNCTION DEFINITION
SHERIN RAPPAI 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
SHERIN RAPPAI 6
# function declaration
def function():
print(“Hello world”)
# calling function
function() # function call
EXAMPLE 2
SHERIN RAPPAI 7
def greet(name):
return "Hello, " + name + "!"
# Calling the function
message = greet(“BCA D ")
print(message) # Output: Hello, BCA D!
The greet function takes a single parameter name and returns a greeting message
FUNCTION PARAMETRES
SHERIN RAPPAI 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.
FUNCTION PARAMETRES
SHERIN RAPPAI 9
TYPES OF FUNCTIONS IN PYTHON
SHERIN RAPPAI 10
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.
SHERIN RAPPAI 11
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:
SHERIN RAPPAI 12
lambda arguments : expression
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
SHERIN RAPPAI 13
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.
SHERIN RAPPAI 14
SHERIN RAPPAI 15
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.
SHERIN RAPPAI 16
RECURSIVE FUNCTION EXAMPLE
 Suppose we want to calculate the factorial value of an integer [n! = n * (n-1)!]
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.
SHERIN RAPPAI 17
SHERIN RAPPAI 18
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:
SHERIN RAPPAI 19
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
SHERIN RAPPAI 20
FUNCTIONS ARGUMENTS
 You can call a function by using this types of
formal parameters
SHERIN RAPPAI 21
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
SHERIN RAPPAI 22
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
SHERIN RAPPAI 23
when you call a function, you usually pass arguments to it. For example:
def student(name, course, fees):
print("Name:", name)
print("Course:", course)
print("Fees:", fees)
Here, name, course, and fees are the parameters of the function.When you call the function
like this:
student("Ashok", "BCA", "30000")
You're passing the arguments by their position. The first value "Ashok" goes to name, the
second "BCA" goes to course, and the third "30000" goes to fees.
SHERIN RAPPAI 24
What are Keyword Arguments?
Keyword arguments allow you to pass values to a function by explicitly stating the name
of the parameter.This means you don't have to follow the exact order of the parameters.
For example, you can call the student function like this:
student(fees="30000", name="Ashok", course="BCA")
Here, you're specifying which value should go to which parameter by using the
parameter name (fees, name, course).This is called keyword arguments.
SHERIN RAPPAI 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
SHERIN RAPPAI 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
SHERIN RAPPAI 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: “, p)
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 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.
SHERIN RAPPAI
SHERIN RAPPAI 29
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.
SHERIN RAPPAI 30
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
SHERIN RAPPAI 31
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!
SHERIN RAPPAI 32
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.
SHERIN RAPPAI 33
my_game/
│
├── characters/ # This is the package
│ ├── __init__.py # This makes 'characters' a package
│ ├── hero.py # A module for the hero character
│ ├── villain.py # A module for the villain character
│ └── sidekick.py # A module for the sidekick character
Example:Let's say you're writing a game with different characters.You might organize your code like this:
# Import the hero, villain, and sidekick from the characters package
from characters.hero import Hero
from characters.villain importVillain
from characters.sidekick import Sidekick
SHERIN RAPPAI 34
What is __init__.py?
In Python, the __init__.py file is an important file used to define a package. It can be empty or contain
initialization code, but its main job is to signal to Python that the directory it is in should be treated as a package.
Why is __init__.py Needed?
Without __init__.py, Python wouldn't recognize a directory as a package. In simple terms, it's like a "flag" that
tells Python, "Hey, treat this folder like a package with related modules inside!“
What Does It Do?
1.Marks a Folder as a Package: When you see a folder with an __init__.py file, that folder is considered a
package. This allows you to import modules from it.
2.Can Contain Initialization Code: You can put code in __init__.py that you want to run when the package is
imported. For example, it can help you load modules, define variables, or set up configurations when the package
is first used.
3.Allows Relative Imports: Inside a package, you can use the __init__.py file to import other modules from the
same package, making the code more modular and organized.
SHERIN RAPPAI 35
Example:
Let’s say you have the following structure in your project:
my_project/
│
├── math_operations/ # This is a package (because of the __init__.py file)
│ ├── __init__.py # Special file that marks the folder as a package
│ ├── addition.py # A module with code for adding numbers
│ └── subtraction.py # A module with code for subtracting numbers
Now, you can import the modules from the math_operations package like this:
from math_operations import addition, subtraction
If the __init__.py file wasn't there, Python wouldn't know that math_operations is a package, and you wouldn't be able to
import these modules.
Can __init__.py Be Empty?
Yes, it can be completely empty! Its only job in this case is to tell Python that the folder is a package. However, you can
also add some code to it if needed.
SHERIN RAPPAI 36
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:
SHERIN RAPPAI 37
def greet(name):
return f"Hello, {name}!"
def square(x):
return x ** 2
SHERIN RAPPAI 38
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
SHERIN RAPPAI 39
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
SHERIN RAPPAI 40
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.
SHERIN RAPPAI 41
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
self:This is a reference to the current instance of the class. It’s like saying "this specific
dog."
SHERIN RAPPAI 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.
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.
SHERIN RAPPAI 43
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.
SHERIN RAPPAI 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.
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.
SHERIN RAPPAI 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.
SHERIN RAPPAI 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.
(These are variables that are shared among all instances (objects) of a class. Every object can access and modify this
shared variable. It's like having one big notebook that everyone can read and write in.)
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
SHERIN RAPPAI 47
Imagine we are modeling a Car for a vehicle fleet system.
ClassVariable:All cars in the fleet might share the same manufacturer.
Class Method:You might want to check how many cars have been added to the fleet.
SHERIN RAPPAI 48
class Car:
manufacturer = "Tesla" # Class variable (shared by all cars)
total_cars = 0 # Class variable to count the number of cars
def __init__(self, model, year):
self.model = model
self.year = year
Car.total_cars += 1 # Increment the total car count each time a car is created
@classmethod
def fleet_count(cls):
return f"Total cars in the fleet: {cls.total_cars}" # Class method to access the total number of
cars
# Creating instances (objects) of the Car class
car1 = Car("Model S", 2022)
car2 = Car("Model X", 2023)
# Accessing the class variable
print(car1.manufacturer) # Output:Tesla
print(car2.manufacturer) # Output:Tesla
# Accessing the class method to check how many cars are in the fleet
print(Car.fleet_count()) # Output:Total cars in the fleet: 2
SHERIN RAPPAI 49
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
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.
SHERIN RAPPAI 50
SHERIN RAPPAI 51
class Car:
manufacturer = "Tesla"
@staticmethod
def calculate_efficiency(distance, fuel_used):
return distance / fuel_used
You could illustrate how the method calculate_efficiency doesn't need to know anything about the car instance or the
class, and you can directly call it with data as a utility function.
manufacturer = "Tesla" is a class variable.This means every car we describe
using this class will have "Tesla" as its manufacturer.
@staticmethod means that this method doesn’t care about the
specific car. It's just a function that calculates fuel efficiency.The
method takes two inputs:
distance (how far the car has traveled) and fuel_used (how much
fuel was used), then it calculates efficiency by dividing the distance by
the fuel used.
SHERIN RAPPAI 52
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.
SHERIN RAPPAI 53
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.
SHERIN RAPPAI 54
A constructor is like a setup method that is automatically called when you create a new
object from a class. It’s used to give your object the basic information it needs as soon as it’s
created. In Python, the constructor is a special method called __init__().
Let’s use the Car example again, but this time we’ll use a constructor to set up important details about each car when
we create it.
class Car:
def __init__(self, model, year):
# This is the constructor method
self.model = model # Set the car's model
self.year = year # Set the car's manufacturing year
__init__(self, model, year):This is the constructor method. It runs automatically when you create a new
car.self.model = model: This means that the model you provide will be saved as a property of the
car.self.year = year: Similarly, the year you provide will be saved as the car’s manufacturing year.
SHERIN RAPPAI 55
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.
SHERIN RAPPAI 56
The __init__ method in Python is a special method that acts as a constructor. It’s automatically called
when you create an object from a class, and it’s used to initialize the object's attributes.
Let’s break it down simply:
What Does the __init__ Method Do?
•Initialization: When you create a new object, the __init__ method helps to set up that object with the
specific details or information you want. It’s like filling out a form when you get a new item, such as
entering your name and email when setting up a new phone or account.
Example Using a Car
Let’s look at how the __init__ method works in a Car class:
class Car:
def __init__(self, model, year): # This is the constructor method
self.model = model # The car's model (e.g., Model S)
self.year = year # The car's manufacturing year (e.g., 2022)
SHERIN RAPPAI 57
How It Works:
1.When you create a car object:
car1 = Car("Model S", 2022)
2.The __init__ method is called automatically:
•Python looks for the __init__ method inside the Car class.
•It sets the model of the car to "Model S", and the year to 2022.
3.Now, the car object car1 has these attributes:
•car1.model is "Model S"
•car1.year is 2022
Why Is This Useful?
The __init__ method allows you to give each car its own specific information when it’s created. Without it, you’d have
to manually assign those values after creating the object, which would be more complicated.
Think of It Like This:
When you order a custom-built car, the factory uses the information you provide (e.g., color, model, year) to build the
car. The constructor (__init__) is like that factory setup process — it ensures that when the car is delivered, it already
has the features you wanted.
SHERIN RAPPAI 58
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.
SHERIN RAPPAI 59
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.
SHERIN RAPPAI 60
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.
SHERIN RAPPAI 61
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).
SHERIN RAPPAI 62
class Animal:
def __init__(self, name):
self.name = name
print(f"Animal named {self.name} is created.")
class Dog(Animal):
def __init__(self, name, breed):
# Call the superclass constructor
super().__init__(name)
self.breed = breed
print(f"Dog breed is {self.breed}")
dog = Dog("Buddy", "Golden Retriever")
Output:
Animal named Buddy is created.
Dog breed is Golden Retriever
super()
SHERIN RAPPAI 63
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.
SHERIN RAPPAI 64
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.
SHERIN RAPPAI 65
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.
SHERIN RAPPAI 66
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.
SHERIN RAPPAI 67
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# Overloading the addition operator (+)
def __add__(self, other):
new_width = self.width + other.width
new_height = self.height + other.height
return Rectangle(new_width, new_height)
# Overloading the string representation (for print)
def __str__(self):
return f"Width: {self.width}, Height: {self.height}"
# Create two Rectangle objects
rect1 = Rectangle(4, 5)
rect2 = Rectangle(3, 2)
# Add the two rectangles
combined_rect = rect1 + rect2
# Print the result
print(combined_rect)
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.
SHERIN RAPPAI 68
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.
SHERIN RAPPAI 69
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
SHERIN RAPPAI 70
5. Specifying PackageVersions:
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
SHERIN RAPPAI 71
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
SHERIN RAPPAI 72
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

Similar to Functions in python, types of functions in python (20)

Chapter 2 Python Functions
Chapter 2               Python FunctionsChapter 2               Python Functions
Chapter 2 Python Functions
11210208
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
KavithaChekuri3
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
Osama Ghandour Geris
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 
Chapter 2 Python Functions
Chapter 2               Python FunctionsChapter 2               Python Functions
Chapter 2 Python Functions
11210208
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
Osama Ghandour Geris
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 

More from SherinRappai (20)

Shells commands, file structure, directory structure.pptx
Shells commands, file structure, directory structure.pptxShells commands, file structure, directory structure.pptx
Shells commands, file structure, directory structure.pptx
SherinRappai
 
Shell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptxShell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptx
SherinRappai
 
Types of NoSql Database available.pptx
Types of NoSql   Database available.pptxTypes of NoSql   Database available.pptx
Types of NoSql Database available.pptx
SherinRappai
 
Introduction to NoSQL & Features of NoSQL.pptx
Introduction to NoSQL & Features of NoSQL.pptxIntroduction to NoSQL & Features of NoSQL.pptx
Introduction to NoSQL & Features of NoSQL.pptx
SherinRappai
 
Clustering, Types of clustering, Types of data
Clustering, Types of clustering, Types of dataClustering, Types of clustering, Types of data
Clustering, Types of clustering, Types of data
SherinRappai
 
Association rule introduction, Market basket Analysis
Association rule introduction, Market basket AnalysisAssociation rule introduction, Market basket Analysis
Association rule introduction, Market basket Analysis
SherinRappai
 
Introduction to Internet, Domain Name System
Introduction to Internet, Domain Name SystemIntroduction to Internet, Domain Name System
Introduction to Internet, Domain Name System
SherinRappai
 
Cascading style sheet, CSS Box model, Table in CSS
Cascading style sheet, CSS Box model, Table in CSSCascading style sheet, CSS Box model, Table in CSS
Cascading style sheet, CSS Box model, Table in CSS
SherinRappai
 
Numpy in python, Array operations using numpy and so on
Numpy in python, Array operations using numpy and so onNumpy in python, Array operations using numpy and so on
Numpy in python, Array operations using numpy and so on
SherinRappai
 
Extensible markup language ppt as part of Internet Technology
Extensible markup language ppt as part of Internet TechnologyExtensible markup language ppt as part of Internet Technology
Extensible markup language ppt as part of Internet Technology
SherinRappai
 
Java script ppt from students in internet technology
Java script ppt from students in internet technologyJava script ppt from students in internet technology
Java script ppt from students in internet technology
SherinRappai
 
Building Competency and Career in the Open Source World
Building Competency and Career in the Open Source WorldBuilding Competency and Career in the Open Source World
Building Competency and Career in the Open Source World
SherinRappai
 
How to Build a Career in Open Source.pptx
How to Build a Career in Open Source.pptxHow to Build a Career in Open Source.pptx
How to Build a Career in Open Source.pptx
SherinRappai
 
Issues in Knowledge representation for students
Issues in Knowledge representation for studentsIssues in Knowledge representation for students
Issues in Knowledge representation for students
SherinRappai
 
A* algorithm of Artificial Intelligence for BCA students
A* algorithm of Artificial Intelligence for BCA studentsA* algorithm of Artificial Intelligence for BCA students
A* algorithm of Artificial Intelligence for BCA students
SherinRappai
 
Unit 2.pptx
Unit 2.pptxUnit 2.pptx
Unit 2.pptx
SherinRappai
 
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
SherinRappai
 
Clustering.pptx
Clustering.pptxClustering.pptx
Clustering.pptx
SherinRappai
 
neuralnetwork.pptx
neuralnetwork.pptxneuralnetwork.pptx
neuralnetwork.pptx
SherinRappai
 
Rendering Algorithms.pptx
Rendering Algorithms.pptxRendering Algorithms.pptx
Rendering Algorithms.pptx
SherinRappai
 
Shells commands, file structure, directory structure.pptx
Shells commands, file structure, directory structure.pptxShells commands, file structure, directory structure.pptx
Shells commands, file structure, directory structure.pptx
SherinRappai
 
Shell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptxShell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptx
SherinRappai
 
Types of NoSql Database available.pptx
Types of NoSql   Database available.pptxTypes of NoSql   Database available.pptx
Types of NoSql Database available.pptx
SherinRappai
 
Introduction to NoSQL & Features of NoSQL.pptx
Introduction to NoSQL & Features of NoSQL.pptxIntroduction to NoSQL & Features of NoSQL.pptx
Introduction to NoSQL & Features of NoSQL.pptx
SherinRappai
 
Clustering, Types of clustering, Types of data
Clustering, Types of clustering, Types of dataClustering, Types of clustering, Types of data
Clustering, Types of clustering, Types of data
SherinRappai
 
Association rule introduction, Market basket Analysis
Association rule introduction, Market basket AnalysisAssociation rule introduction, Market basket Analysis
Association rule introduction, Market basket Analysis
SherinRappai
 
Introduction to Internet, Domain Name System
Introduction to Internet, Domain Name SystemIntroduction to Internet, Domain Name System
Introduction to Internet, Domain Name System
SherinRappai
 
Cascading style sheet, CSS Box model, Table in CSS
Cascading style sheet, CSS Box model, Table in CSSCascading style sheet, CSS Box model, Table in CSS
Cascading style sheet, CSS Box model, Table in CSS
SherinRappai
 
Numpy in python, Array operations using numpy and so on
Numpy in python, Array operations using numpy and so onNumpy in python, Array operations using numpy and so on
Numpy in python, Array operations using numpy and so on
SherinRappai
 
Extensible markup language ppt as part of Internet Technology
Extensible markup language ppt as part of Internet TechnologyExtensible markup language ppt as part of Internet Technology
Extensible markup language ppt as part of Internet Technology
SherinRappai
 
Java script ppt from students in internet technology
Java script ppt from students in internet technologyJava script ppt from students in internet technology
Java script ppt from students in internet technology
SherinRappai
 
Building Competency and Career in the Open Source World
Building Competency and Career in the Open Source WorldBuilding Competency and Career in the Open Source World
Building Competency and Career in the Open Source World
SherinRappai
 
How to Build a Career in Open Source.pptx
How to Build a Career in Open Source.pptxHow to Build a Career in Open Source.pptx
How to Build a Career in Open Source.pptx
SherinRappai
 
Issues in Knowledge representation for students
Issues in Knowledge representation for studentsIssues in Knowledge representation for students
Issues in Knowledge representation for students
SherinRappai
 
A* algorithm of Artificial Intelligence for BCA students
A* algorithm of Artificial Intelligence for BCA studentsA* algorithm of Artificial Intelligence for BCA students
A* algorithm of Artificial Intelligence for BCA students
SherinRappai
 
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
SherinRappai
 
neuralnetwork.pptx
neuralnetwork.pptxneuralnetwork.pptx
neuralnetwork.pptx
SherinRappai
 
Rendering Algorithms.pptx
Rendering Algorithms.pptxRendering Algorithms.pptx
Rendering Algorithms.pptx
SherinRappai
 
Ad

Recently uploaded (20)

Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Ad

Functions in python, types of functions in python

  • 1. UNIT 2: FUNCTIONS IN PYTHON SHERIN RAPPAI 1
  • 2. FUNCTION SHERIN RAPPAI 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 ? SHERIN RAPPAI 3
  • 4. SYNTAX OF FUNCTION DEFINITION SHERIN RAPPAI 4
  • 5. EXAMPLE OF FUNCTION DEFINITION SHERIN RAPPAI 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 SHERIN RAPPAI 6 # function declaration def function(): print(“Hello world”) # calling function function() # function call
  • 7. EXAMPLE 2 SHERIN RAPPAI 7 def greet(name): return "Hello, " + name + "!" # Calling the function message = greet(“BCA D ") print(message) # Output: Hello, BCA D! The greet function takes a single parameter name and returns a greeting message
  • 8. FUNCTION PARAMETRES SHERIN RAPPAI 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.
  • 10. TYPES OF FUNCTIONS IN PYTHON SHERIN RAPPAI 10
  • 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. SHERIN RAPPAI 11
  • 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: SHERIN RAPPAI 12 lambda arguments : expression add = lambda x, y: x + y result = add(5, 3) print(result) # Output: 8
  • 13. SHERIN RAPPAI 13 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
  • 14.  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. SHERIN RAPPAI 14
  • 15. SHERIN RAPPAI 15 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.
  • 16. SHERIN RAPPAI 16 RECURSIVE FUNCTION EXAMPLE  Suppose we want to calculate the factorial value of an integer [n! = n * (n-1)!] def factorial(n): if n == 0: return 1 else return n * factorial (n-1) print(factorial(5)) # output will be 120
  • 17. 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. SHERIN RAPPAI 17
  • 18. SHERIN RAPPAI 18 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.
  • 19. Here's the basic syntax for defining a user-defined function: Here's an example of a simple user-defined function: SHERIN RAPPAI 19 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
  • 20. SHERIN RAPPAI 20 FUNCTIONS ARGUMENTS  You can call a function by using this types of formal parameters
  • 21. SHERIN RAPPAI 21 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
  • 22. SHERIN RAPPAI 22 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
  • 23. SHERIN RAPPAI 23 when you call a function, you usually pass arguments to it. For example: def student(name, course, fees): print("Name:", name) print("Course:", course) print("Fees:", fees) Here, name, course, and fees are the parameters of the function.When you call the function like this: student("Ashok", "BCA", "30000") You're passing the arguments by their position. The first value "Ashok" goes to name, the second "BCA" goes to course, and the third "30000" goes to fees.
  • 24. SHERIN RAPPAI 24 What are Keyword Arguments? Keyword arguments allow you to pass values to a function by explicitly stating the name of the parameter.This means you don't have to follow the exact order of the parameters. For example, you can call the student function like this: student(fees="30000", name="Ashok", course="BCA") Here, you're specifying which value should go to which parameter by using the parameter name (fees, name, course).This is called keyword arguments.
  • 25. SHERIN RAPPAI 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. SHERIN RAPPAI 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. SHERIN RAPPAI 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: “, p) 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 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. SHERIN RAPPAI
  • 29. SHERIN RAPPAI 29 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.
  • 30. SHERIN RAPPAI 30 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
  • 31. SHERIN RAPPAI 31 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!
  • 32. SHERIN RAPPAI 32 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.
  • 33. SHERIN RAPPAI 33 my_game/ │ ├── characters/ # This is the package │ ├── __init__.py # This makes 'characters' a package │ ├── hero.py # A module for the hero character │ ├── villain.py # A module for the villain character │ └── sidekick.py # A module for the sidekick character Example:Let's say you're writing a game with different characters.You might organize your code like this: # Import the hero, villain, and sidekick from the characters package from characters.hero import Hero from characters.villain importVillain from characters.sidekick import Sidekick
  • 34. SHERIN RAPPAI 34 What is __init__.py? In Python, the __init__.py file is an important file used to define a package. It can be empty or contain initialization code, but its main job is to signal to Python that the directory it is in should be treated as a package. Why is __init__.py Needed? Without __init__.py, Python wouldn't recognize a directory as a package. In simple terms, it's like a "flag" that tells Python, "Hey, treat this folder like a package with related modules inside!“ What Does It Do? 1.Marks a Folder as a Package: When you see a folder with an __init__.py file, that folder is considered a package. This allows you to import modules from it. 2.Can Contain Initialization Code: You can put code in __init__.py that you want to run when the package is imported. For example, it can help you load modules, define variables, or set up configurations when the package is first used. 3.Allows Relative Imports: Inside a package, you can use the __init__.py file to import other modules from the same package, making the code more modular and organized.
  • 35. SHERIN RAPPAI 35 Example: Let’s say you have the following structure in your project: my_project/ │ ├── math_operations/ # This is a package (because of the __init__.py file) │ ├── __init__.py # Special file that marks the folder as a package │ ├── addition.py # A module with code for adding numbers │ └── subtraction.py # A module with code for subtracting numbers Now, you can import the modules from the math_operations package like this: from math_operations import addition, subtraction If the __init__.py file wasn't there, Python wouldn't know that math_operations is a package, and you wouldn't be able to import these modules. Can __init__.py Be Empty? Yes, it can be completely empty! Its only job in this case is to tell Python that the folder is a package. However, you can also add some code to it if needed.
  • 36. SHERIN RAPPAI 36 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:
  • 37. SHERIN RAPPAI 37 def greet(name): return f"Hello, {name}!" def square(x): return x ** 2
  • 38. SHERIN RAPPAI 38 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
  • 39. SHERIN RAPPAI 39 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
  • 40. SHERIN RAPPAI 40 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.
  • 41. SHERIN RAPPAI 41 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 self:This is a reference to the current instance of the class. It’s like saying "this specific dog."
  • 42. SHERIN RAPPAI 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. 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.
  • 43. SHERIN RAPPAI 43 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.
  • 44. SHERIN RAPPAI 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. 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.
  • 45. SHERIN RAPPAI 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. SHERIN RAPPAI 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. (These are variables that are shared among all instances (objects) of a class. Every object can access and modify this shared variable. It's like having one big notebook that everyone can read and write in.) 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. SHERIN RAPPAI 47 Imagine we are modeling a Car for a vehicle fleet system. ClassVariable:All cars in the fleet might share the same manufacturer. Class Method:You might want to check how many cars have been added to the fleet.
  • 48. SHERIN RAPPAI 48 class Car: manufacturer = "Tesla" # Class variable (shared by all cars) total_cars = 0 # Class variable to count the number of cars def __init__(self, model, year): self.model = model self.year = year Car.total_cars += 1 # Increment the total car count each time a car is created @classmethod def fleet_count(cls): return f"Total cars in the fleet: {cls.total_cars}" # Class method to access the total number of cars # Creating instances (objects) of the Car class car1 = Car("Model S", 2022) car2 = Car("Model X", 2023) # Accessing the class variable print(car1.manufacturer) # Output:Tesla print(car2.manufacturer) # Output:Tesla # Accessing the class method to check how many cars are in the fleet print(Car.fleet_count()) # Output:Total cars in the fleet: 2
  • 49. SHERIN RAPPAI 49 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
  • 50. 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. SHERIN RAPPAI 50
  • 51. SHERIN RAPPAI 51 class Car: manufacturer = "Tesla" @staticmethod def calculate_efficiency(distance, fuel_used): return distance / fuel_used You could illustrate how the method calculate_efficiency doesn't need to know anything about the car instance or the class, and you can directly call it with data as a utility function. manufacturer = "Tesla" is a class variable.This means every car we describe using this class will have "Tesla" as its manufacturer. @staticmethod means that this method doesn’t care about the specific car. It's just a function that calculates fuel efficiency.The method takes two inputs: distance (how far the car has traveled) and fuel_used (how much fuel was used), then it calculates efficiency by dividing the distance by the fuel used.
  • 52. SHERIN RAPPAI 52 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.
  • 53. SHERIN RAPPAI 53 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.
  • 54. SHERIN RAPPAI 54 A constructor is like a setup method that is automatically called when you create a new object from a class. It’s used to give your object the basic information it needs as soon as it’s created. In Python, the constructor is a special method called __init__(). Let’s use the Car example again, but this time we’ll use a constructor to set up important details about each car when we create it. class Car: def __init__(self, model, year): # This is the constructor method self.model = model # Set the car's model self.year = year # Set the car's manufacturing year __init__(self, model, year):This is the constructor method. It runs automatically when you create a new car.self.model = model: This means that the model you provide will be saved as a property of the car.self.year = year: Similarly, the year you provide will be saved as the car’s manufacturing year.
  • 55. SHERIN RAPPAI 55 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.
  • 56. SHERIN RAPPAI 56 The __init__ method in Python is a special method that acts as a constructor. It’s automatically called when you create an object from a class, and it’s used to initialize the object's attributes. Let’s break it down simply: What Does the __init__ Method Do? •Initialization: When you create a new object, the __init__ method helps to set up that object with the specific details or information you want. It’s like filling out a form when you get a new item, such as entering your name and email when setting up a new phone or account. Example Using a Car Let’s look at how the __init__ method works in a Car class: class Car: def __init__(self, model, year): # This is the constructor method self.model = model # The car's model (e.g., Model S) self.year = year # The car's manufacturing year (e.g., 2022)
  • 57. SHERIN RAPPAI 57 How It Works: 1.When you create a car object: car1 = Car("Model S", 2022) 2.The __init__ method is called automatically: •Python looks for the __init__ method inside the Car class. •It sets the model of the car to "Model S", and the year to 2022. 3.Now, the car object car1 has these attributes: •car1.model is "Model S" •car1.year is 2022 Why Is This Useful? The __init__ method allows you to give each car its own specific information when it’s created. Without it, you’d have to manually assign those values after creating the object, which would be more complicated. Think of It Like This: When you order a custom-built car, the factory uses the information you provide (e.g., color, model, year) to build the car. The constructor (__init__) is like that factory setup process — it ensures that when the car is delivered, it already has the features you wanted.
  • 58. SHERIN RAPPAI 58 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.
  • 59. SHERIN RAPPAI 59 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.
  • 60. SHERIN RAPPAI 60 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.
  • 61. SHERIN RAPPAI 61 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).
  • 62. SHERIN RAPPAI 62 class Animal: def __init__(self, name): self.name = name print(f"Animal named {self.name} is created.") class Dog(Animal): def __init__(self, name, breed): # Call the superclass constructor super().__init__(name) self.breed = breed print(f"Dog breed is {self.breed}") dog = Dog("Buddy", "Golden Retriever") Output: Animal named Buddy is created. Dog breed is Golden Retriever super()
  • 63. SHERIN RAPPAI 63 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.
  • 64. SHERIN RAPPAI 64 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.
  • 65. SHERIN RAPPAI 65 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.
  • 66. SHERIN RAPPAI 66 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.
  • 67. SHERIN RAPPAI 67 class Rectangle: def __init__(self, width, height): self.width = width self.height = height # Overloading the addition operator (+) def __add__(self, other): new_width = self.width + other.width new_height = self.height + other.height return Rectangle(new_width, new_height) # Overloading the string representation (for print) def __str__(self): return f"Width: {self.width}, Height: {self.height}" # Create two Rectangle objects rect1 = Rectangle(4, 5) rect2 = Rectangle(3, 2) # Add the two rectangles combined_rect = rect1 + rect2 # Print the result print(combined_rect) 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.
  • 68. SHERIN RAPPAI 68 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.
  • 69. SHERIN RAPPAI 69 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
  • 70. SHERIN RAPPAI 70 5. Specifying PackageVersions: 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
  • 71. SHERIN RAPPAI 71 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
  • 72. SHERIN RAPPAI 72 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.

Editor's Notes

  • #29: The sys module in Python provides access to system-specific parameters and functions. It allows interaction with the Python runtime environment, such as accessing command-line arguments, manipulating the Python path, and managing the standard input/output streams. Example usage: python import sys # Get the list of command-line arguments print(sys.argv) # Get the Python version print(sys.version) # Exit the program sys.exit()
  • #31: These custom modules can be used to organize and reuse your code. Organizing code: Custom modules help you organize your code, making it more modular and reusable.
  • #32: In Python, a package is a way to organize and group related modules into a directory structure, allowing for better code organization and reusability. A package consists of a directory that contains Python files (modules) and a special file named __init__.py to indicate that the directory should be treated as a package.
  • #33: This structure represents a Python package named characters within a directory called my_game. The package characters contains multiple modules (hero.py, villain.py, and sidekick.py), which are each responsible for different characters in the game. Here's a detailed explanation of each part: 1. my_game/ This is the root directory of your game project. It contains various components, such as the characters package, that handle different aspects of the game. 2. characters/ This is a package that groups together related modules, specifically focusing on characters in the game. The purpose of this package is to organize different character-related functionalities into separate modules. 3. __init__.py This special file tells Python that the characters/ directory is a package. It can be empty or include code that should be run when the package is imported. In this case, it just indicates that the characters directory is a valid Python package, allowing you to import from it.
  • #34: __init__.py: This is a special file that signals to Python that the directory should be treated as a package. It can be empty or can include initialization code for the package. In modern Python versions, it's not always necessary for the directory to contain this file, but it's still good practice. # __init__.py print("Initializing my_package") app_version = "1.0.0“ Relative imports allow you to import modules from within the same package without specifying the full path. This is useful for keeping your code clean and maintaining the package's modularity. In relative imports, you use a dot (.) to refer to the current package or module you're in, and more dots (..) to move up the directory structure. This keeps everything within the package, without having to write the entire module path. # __init__.py # Relative imports within the package from .hero import Hero from .villain import Villain from .sidekick import Sidekick from characters import Hero, Villain, Sidekick rather than using from characters.hero import Hero from characters.villain import Villain from characters.sidekick import Sidekick Summary of Relative Imports Relative imports allow you to import modules from within the same package without specifying their full paths. In __init__.py, you can use a relative import (from .module_name import Class) to import modules from the same package. This helps in keeping your code organized and modular. You don't have to repeat long paths, just use dots (.) to refer to modules within the package. This way, you can build complex packages with multiple modules working together seamlessly, without needing to explicitly write full paths every time you import something.
  • #38: If my_module.py is not in the same directory as your main script, Python needs to know where to look for it. Python maintains a list of directories where it searches for modules. This list is stored in a variable called sys.path. sys.path is a list of directories that Python searches for when you try to import a module. By default, it includes: The directory containing the script you're running. Standard library directories. Any directories added manually to the sys.path list.
  • #41: The __init__ method is a special method in Python known as the constructor. It's automatically called when a new instance of the class is created.The method takes three arguments: self, name, and age.self refers to the instance of the class itself, which allows access to its attributes and methods. name and age are the parameters passed when creating a Dog object.
  • #43: Blueprint for a Person (Class): Imagine you're a clothing designer, and you have a template for making shirts. Each shirt has a size, color, and style, but they all follow the same template. In the same way, the Human class is like a template for people. It defines what information each person has, like their name and age. Making a New Person (Constructor): When you make a new shirt, you decide its size and color. Similarly, when you create a person using this template (i.e., when the constructor runs), you provide the person’s name and age. For example, when we say Alice = Human("Alice", 25), we’re creating a new person named Alice who is 25 years old. The constructor takes the name and age you provide and builds the person using that information. Self = "This Specific Person": self is a bit like saying "this specific person" when you're talking about them. If you had multiple shirts, you'd want to make sure you're talking about this shirt, not another one. The same goes for people in our class. When we say self.name, we’re talking about this person’s name. So if Alice wants to introduce herself, she’ll use her own name, and Bob will use his own name, even though they were both created from the same blueprint. Doing Things (Methods): Now, once Alice or Bob is created, they can do things like introduce themselves or have a birthday. When Alice calls the introduce() method, it’s like she’s saying, "Hi, my name is Alice and I am 25 years old." But when Bob calls it, he says, "Hi, my name is Bob and I am 30 years old." Even though they both have the same introduce() function, it works differently for each person because of the self keyword. Simplified Example: Imagine you had a paper form for registering people for an event. Every time someone signs up, they fill in their name and age. The form itself is always the same, but each person fills it out with their own information. The class is the form template. The constructor is like filling out the form for each new person. self is how the computer knows that this specific form belongs to Alice, and that form belongs to Bob. So when Alice has a birthday, she adds a year to her age, but Bob's age stays the same because they have their own forms (own data).
  • #49: This Python code defines a Car class with class variables, instance variables, and a class method. It demonstrates how object-oriented principles like class variables and methods are used. Here's a detailed explanation: 1. Class Definition: python Copy code class Car: This defines a class named Car. A class in Python is a blueprint for creating objects (instances), and in this case, it's a blueprint for creating different car objects. 2. Class Variables: python Copy code manufacturer = "Tesla" total_cars = 0 manufacturer = "Tesla": This is a class variable, meaning it belongs to the class itself rather than any particular object (instance). All instances of the class will share the same manufacturer value, which is set to "Tesla". total_cars = 0: This is another class variable that keeps track of the total number of Car objects created. Every time a new Car object is instantiated, this variable is incremented. 3. Constructor (__init__ Method): python Copy code def __init__(self, model, year): self.model = model self.year = year Car.total_cars += 1 The __init__ method is a constructor that is called every time a new object of the class is created. It initializes instance-specific attributes. self.model = model: Here, self.model is an instance variable. It's different for each car instance (e.g., "Model S" for one car, "Model X" for another). self.year = year: Another instance variable, specific to each instance, storing the car's production year. Car.total_cars += 1: This increments the class variable total_cars by 1 every time a new car object is created, keeping track of the total number of cars created. 4. Class Method: python Copy code @classmethod def fleet_count(cls): return f"Total cars in the fleet: {cls.total_cars}" @classmethod: This is a decorator that designates fleet_count as a class method. Class methods take cls (referring to the class itself) as the first argument, instead of self (which refers to an instance). cls.total_cars: Inside this method, cls is used to access the class variable total_cars. This allows the method to return the total number of Car instances created. f"Total cars in the fleet: {cls.total_cars}": This is an f-string (formatted string), which returns a string showing the total number of cars. 5. Creating Objects (Instances): python Copy code car1 = Car("Model S", 2022) car2 = Car("Model X", 2023) Here, two Car objects are created: car1 is an instance representing a Tesla Model S made in 2022. car2 is an instance representing a Tesla Model X made in 2023. Each time an object is created, the constructor (__init__) is called, and Car.total_cars is incremented by 1. So, after creating both cars, the total_cars class variable is now 2. 6. Accessing Class Variables: python Copy code print(car1.manufacturer) # Output: Tesla print(car2.manufacturer) # Output: Tesla Both car1 and car2 are instances of the Car class, and they can access the class variable manufacturer. Since manufacturer is a class variable (shared by all instances), both cars have the value "Tesla". 7. Using the Class Method: python Copy code print(Car.fleet_count()) # Output: Total cars in the fleet: 2 The class method fleet_count() is called to return the total number of cars created. Since Car.total_cars was incremented twice (once for each car), the output is "Total cars in the fleet: 2". Key Concepts: Class Variables: Variables shared by all instances of the class. In this case, manufacturer and total_cars are class variables. Instance Variables: Variables specific to each instance. Here, model and year are instance variables. Class Methods: Methods that can be called on the class itself (without needing an instance), as shown with fleet_count(). Constructor (__init__): Initializes each new object with instance-specific values. It also increments the
  • #50: A utility function in programming refers to a function that performs a general or common task, often reusable across different parts of a program. These functions are typically designed to handle routine operations that don't necessarily depend on specific objects or instances, but instead provide helpful services that can be used anywhere in the code.
  • #66: Certainly! Operator overloading in Python allows you to define how operators (like +, -, *, etc.) behave with objects of your own classes. This means you can customize what happens when you use these operators with instances of your class. Simple Explanation What It Is: Operator overloading means defining or customizing the behavior of operators for your custom class. For instance, you can tell Python what should happen when you use the + operator with your class.
  • #70: The pip freeze command outputs a list of all the Python packages installed in the current environment and their versions. package_name==version numpy==1.21.0 pandas==1.3.0 The > symbol is a shell operator used to redirect the output of a command into a file. In this case, it redirects the output of pip freeze into a file named requirements.txt.
  • #71: The requirements.txt file is a common way to list all the dependencies needed for a project. Other developers or users can recreate the same environment by installing the exact versions of the dependencies listed in the file.Share Dependencies: When sharing your code (e.g., on GitHub), including a requirements.txt file helps others install the necessary packages to run the project by using:
  • #72: If you don't use virtual environments and install packages globally (on the system-wide Python), there are several risks that can cause interference with other projects or the system Python installation itself: Dependency Conflicts: Different projects may require different versions of the same package. For example, one project might require Django 3.0 while another needs Django 4.0. If you install both globally, one version will overwrite the other. This can break whichever project expects the overwritten version. Harder Debugging: Without a virtual environment, it becomes difficult to track which project is using which dependencies. This can make debugging and maintaining projects challenging, as you may encounter unexpected behavior due to shared packages.