Unit 2 - Functions in Python[1]
Unit 2 - Functions in Python[1]
VISHNU PRIYA P M 1
FUNCTION
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
2
VISHNU PRIYA P M
HOW FUNCTION WORKS ?
VISHNU PRIYA P M 3
SYNTAX OF FUNCTION DEFINITION
VISHNU PRIYA P M 4
EXAMPLE OF FUNCTION DEFINITION
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.
VISHNU PRIYA P M 5
EXAMPLE 1
# function declaration
def function():
print(“Hello world”)
# calling function
function() # function call
VISHNU PRIYA P M 6
EXAMPLE 2
def greet(name):
return "Hello, " + name + "!"
The greet function takes a single parameter name and returns a greeting message
VISHNU PRIYA P M 7
FUNCTION PARAMETRES
VISHNU PRIYA P M 9
TYPES OF FUNCTIONS IN PYTHON
VISHNU PRIYA P M 10
ANONYMOUS FUNCTIONS
VISHNU PRIYA P M 11
ANONYMOUS FUNCTIONS
lambda arguments :
expression
Here's a basic example of a lambda function that adds two numbers:
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
VISHNU PRIYA P M 12
ANONYMOUS FUNCTIONS
VISHNU PRIYA P M 13
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.
Lambda functions can be useful in situations where defining a full named function might
be unnecessary due to the function's simplicity.
However, for more complex or larger functions, it's generally better to use regular user-
defined functions for clarity and maintainability.
VISHNU PRIYA P M 14
RECURSIVE FUNCTIONS
def factorial(n):
if n == 0:
return 1
else
return n * factorial (n-1)
VISHNU PRIYA P M 16
calculating the factorial of a non-negative integer n:
def factorial(n): The factorial function calls itself with a smaller
if n == 0: value of n until it reaches the base case where n is 0.
return 1 This base case returns 1, and the function then starts
else: "unwinding" the recursive calls, multiplying each
return n * factorial(n - 1) value of n until the original call is complete.
When creating recursive functions, it's important to define the base case(s) that will
terminate the recursion and prevent infinite loops.
Without a proper base case, the function would keep calling itself indefinitely and
eventually lead to a "RecursionError" due to exceeding the maximum recursion depth.
VISHNU PRIYA P M 17
USER-DEFINED FUNCTIONS IN PYTHON
User-defined functions in Python are functions that you create yourself to perform
specific tasks according to your needs.
They allow you to encapsulate a block of code into a reusable unit, making your code
more organized and modular.
To define a user-defined function in Python, you use the def keyword followed by the
function name, a set of parentheses containing any parameters the function takes (if
any), and a colon (:).
The function body is indented and contains the code that defines what the function
does.
You can also include a return statement to send a value back as the result of the
function's execution.
VISHNU PRIYA P M 18
Here's the basic syntax for defining a user-defined function:
def function_name(parameters):
# Function body
# Code to perform the task
return result # Optional
result = add_numbers(5, 3)
print(result) # Output: 8
VISHNU PRIYA P M 19
FUNCTIONS ARGUMENTS
VISHNU PRIYA P M 20
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
VISHNU PRIYA P M 21
2. KEYWORD
ARGUMENTS
VISHNU PRIYA P M 22
when you call a function, you usually pass arguments to it. For example:
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.
VISHNU PRIYA P M 23
What are Keyword Arguments?
For example, you can call the student function like this:
VISHNU PRIYA P M 24
2. KEYWORD
ARGUMENTS
VISHNU PRIYA P M 25
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
VISHNU PRIYA P M 26
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.
28
VISHNU PRIYA P M
Introduction to working with modules in Python:
VISHNU PRIYA P M 29
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
You can also use the from keyword to import specific items from a module:
VISHNU PRIYA P M 30
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}!"
import my_module
message = my_module.greet("Alice")
print(message) # Output: Hello, Alice!
VISHNU PRIYA P M 31
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.
Common third-party modules include numpy, pandas, requests, and many others.
Using modules in Python promotes code reusability and helps manage the complexity
of larger projects. By breaking down your code into smaller, modular components, you
can work more efficiently and collaborate effectively with other developers.
VISHNU PRIYA P M 32
Example:Let's say you're writing a game with different characters. You might organize your code
like this:
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
VISHNU PRIYA P M 33
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!“
VISHNU PRIYA P M 34
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:
VISHNU PRIYA P M 35
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.
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)
VISHNU PRIYA P M 36
How It Works:
1.When you create a car object:
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.
def square(x):
return x ** 2
VISHNU PRIYA P M 39
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).
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.
VISHNU PRIYA P M
import my_module 40
. Use functions from the module in your script:
message = my_module.greet("Alice")
print(message) # Output: Hello, Alice!
result = my_module.square(5)
print(result) # Output: 25
VISHNU PRIYA P M 41
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:
message = greet("Bob")
print(message) # Output: Hello, Bob!
Keep in mind that the name of the module (e.g., my_module) acts as a namespace for the
functions and variables defined within it. This helps prevent naming conflicts between different
modules.
VISHNU PRIYA P M 42
CLASSES AND OBJECTS
Class
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
class Dog: the class's body.
def __init__(self, name, age):
self.name = nameself: This is a reference to the current instance of the class. It’s like
saying "this specific dog."
self.age = age
def bark(self):
return "Woof!"
VISHNU PRIYA P M 43
In this example, we've defined a Dog class with attributes name and age, and a method bark()
Object:
An object is an instance of a class. It's a concrete entity that can hold data (attributes)
and perform actions (methods) as defined by the class. To create an object, you call the
class as if it were a function, which creates a new instance of that class.
my_dog = Dog("Buddy", 3)
In this case, my_dog is an object of the Dog class with the name attribute set to "Buddy" and
the age attribute set to 3.
VISHNU PRIYA P M 44
Using Objects:
You can access the attributes and methods of an object using the dot (.) notation:
The __init__ method is a special method called a constructor. It's used to initialize the
attributes of an object when it's created. The self parameter refers to the object itself
and is used to access its attributes and methods.
VISHNU PRIYA P M 45
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."
class properties are attributes associated with a class that have special behavior when
accessed or modified. They provide a way to encapsulate and control the access to
class-level data.
There are two main types of class properties:
class variables and class methods.
VISHNU PRIYA P M 47
Class Variables:
Class variables are shared among all instances of a class. They are
defined within the class scope but outside any methods. Class variables
are accessible using the class name and can also be accessed through
instances of the class. They are often used to store data that is
common to all instances of the class.
(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
obj1 = MyClass(10)
VISHNU PRIYA P M
obj2 = MyClass(20) 48
print(obj1.class_variable) # Output: 0
Imagine we are modeling a Car for a vehicle fleet system.
Class Variable: 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.
VISHNU PRIYA P M 49
class Car:
manufacturer = "Tesla" # Class variable (shared by all cars)
total_cars = 0 # Class variable to count the number of cars
@classmethod
def fleet_count(cls):
return f"Total cars in the fleet: {cls.total_cars}" # Class method to access the
total number of cars
# Accessing the class method to check how many cars are in the fleet
print(Car.fleet_count()) # Output: Total cars in the fleet: 2
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
@classmethod
def modify_class_variable(cls, new_value):
cls.class_variable = new_value
obj1 = MyClass(10)
obj2 = MyClass(20)
VISHNU PRIYA P M
obj1.modify_class_variable(5) 51
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.
VISHNU PRIYA P M 52
class Car: manufacturer = "Tesla" is a class variable. This means every car
manufacturer = "Tesla" we describe using this class will have "Tesla" as its
manufacturer.
@staticmethod
def calculate_efficiency(distance, @staticmethod means that this method doesn’t care
fuel_used): about the specific car. It's just a function that calculates
return distance / fuel_used 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.
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.
VISHNU PRIYA P M 53
class MathUtils:
@staticmethod In this example, the add and subtract methods are
def add(x, y): static methods because they don't access any
return x + y instance-specific or class-specific data. They
perform basic arithmetic operations and are
@staticmethod associated with the MathUtils class, but they can
def subtract(x, y): be called using the class name without creating
return x - y instances of the class.
result1 = MathUtils.add(5, 3)
result2 = MathUtils.subtract(10, 2)
print(result1) # Output: 8
print(result2) # Output: 8
VISHNU PRIYA P M 54
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
the __init__ method is the constructor for the # Creating objects using the constructor
Person class. It takes two parameters, name and person1 = Person("Alice", 30)
age, and initializes the corresponding attributes of person2 = Person("Bob", 25)
the object being created using those values.
# Accessing object attributes
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
VISHNU PRIYA P M 55
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.
VISHNU PRIYA P M 56
Key points about constructors in Python:
VISHNU PRIYA P M 58
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.(The method in the subclass must have the same
name and parameters as the one in the parent class. This keeps the
method signatures identical so that the subclass method can replace or
extend the functionality of the parent class method.)
animal = Animal()
dog = Dog()
cat = Cat()
class Animal(object):
def __init__(self, animal_type):
print('Animal Type:', animal_type)
class Mammal(Animal):
def __init__(self):
# call superclass
super().__init__('Mammal')
print('Mammals give birth directly')
dog = Mammal()
VISHNU PRIYA P M 62
INHERITANCE
def speak(self):
return "Animal speaks"
class Dog(Animal): Animal is the base class, and Dog and Cat are
def speak(self): subclasses that inherit from Animal. The
return "Woof" subclasses override the speak method to provide
their own implementations, while still inheriting
class Cat(Animal): the __init__ method and attribute from the Animal
def speak(self): class.
return "Meow"
dog = Dog("Buddy")
cat = Cat("Whiskers")
VISHNU PRIYA P M 66
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
pip is the package installer for Python. It's a command-line tool that allows you to
install and manage Python packages, which are pre-written libraries or modules that
provide specific functionality and can be easily reused in your own projects. Python
packages are typically published and shared on the Python Package Index (PyPI), a
repository of open-source Python packages.
VISHNU PRIYA P M 68
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
4. Uninstalling Packages:
To uninstall a package, you use the command pip uninstall package_name
VISHNU PRIYA P M 69
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:
VISHNU PRIYA P M 70
7. Installing from a Requirements File:
8. Upgrading Packages:
To upgrade a package to the latest version, use the command:
VISHNU PRIYA P M 71
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).