0% found this document useful (0 votes)
32 views

Functions

The document discusses Python functions including built-in and user-defined functions. It provides examples of common built-in functions such as print(), len(), sorted(), type(), range(), input(), max(), min(), and sum() which are used for tasks like output, length calculation, sorting, type checking, generating sequences, user input, and aggregation. Functions allow code reusability, modularity, and organization to write efficient and manageable Python programs.

Uploaded by

Rajan Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Functions

The document discusses Python functions including built-in and user-defined functions. It provides examples of common built-in functions such as print(), len(), sorted(), type(), range(), input(), max(), min(), and sum() which are used for tasks like output, length calculation, sorting, type checking, generating sequences, user input, and aggregation. Functions allow code reusability, modularity, and organization to write efficient and manageable Python programs.

Uploaded by

Rajan Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Agenda

In this class we will discuss about Python Functions:

• What is Function
• Application of python function
• Types of Function
• Types of built in function
• Types of user defined function
• Arguments in function
• Difference b/w arguments and parameters
• Lambda Function

Functions
Functions in Python are named blocks of code that are designed to perform a specific task or a
series of related tasks. In the world of Python programming, functions are like specialized tools
that can perform specific tasks for you. Think of them as helpful assistants that you can call upon
whenever you need their expertise.

Each function has its own unique name and purpose. For instance, there's a popular function
called "print" that comes in handy when you want to display information on the screen. By
invoking the "print" function and providing it with the message you want to share, it takes care
of showing that message on the screen for you and anyone using your program.

Another useful function is "len," which excels at counting things. Whether you have a word, a
sentence, or a list of items, you can call the "len" function and provide it with the object you want
to measure. It will swiftly analyze the object and provide you with the number representing its
length.

Functions don't stop at just printing and counting. They possess the power to convert data from
one form to another. For example, there's a versatile function called "str" that transforms
various types of objects into strings. It can take numbers, words, or other data types and convert
them into text format. This ability allows you to display them as output or combine them with
other strings seamlessly.

Beyond these examples, there is a vast array of functions available in Python. They cater to
diverse needs such as performing mathematical calculations, manipulating text, reading and
writing files, interacting with users, and much more. These functions are designed to simplify
programming tasks and enhance your productivity.

So, the next time you encounter a programming challenge, remember the power of functions.
Simply call upon them by their names, provide any necessary input, and watch as they work their
magic to accomplish the tasks you require. Functions are the reliable allies that make your
Python code efficient, organized, and effective.
Real life applications of Python functions
• Reusability: Functions can be reused throughout a program or across different programs,
allowing developers to write efficient and modular code that can be easily modified and
extended.
• Modularity: Functions can be used to break up large programs into smaller, more
manageable units of code, making it easier to debug and maintain the code.
• Code organization: Functions can be used to organize code into logical units that
perform specific tasks, making it easier to navigate and understand the code.

Types of Functions
• Built-in:- In Python, built-in functions are functions that are included in the Python
interpreter by default and can be used without needing to import any external
libraries.

• user-defined:- A user-defined function in Python is a custom block of code that you


create yourself to perform a specific task. You can reuse it throughout your program
by calling its name and passing any required arguments. It helps to organize and
reuse code in larger programs.

• map function:- The map() function is a built-in function that applies a specified
function to each item of an iterable (such as a list, tuple, or string) and returns an
iterator containing the results. It takes two arguments: the function to be applied
and the iterable on which the function will be applied.

• Filter function:- The filter() function is a built-in function that takes in two
arguments: a function and an iterable (such as a list, tuple, or string). It creates a
new iterator that contains only the elements from the original iterable for which the
provided function returns True.

• Reduce Function:- The reduce() function is a built-in function that applies a


specified function to an iterable (e.g., a list, tuple, or string) and returns a single
value. It repeatedly applies the function to the elements of the iterable, reducing
them to a single accumulated value. The function takes two arguments: the function
itself and the iterable.

Built-in Function:-
In Python, a built-in function refers to a function that is pre-defined in the Python programming
language and is readily available for use without the need for any additional imports or external
libraries. These functions are part of the Python standard library and are designed to perform
commonly used operations efficiently.

Python provides a wide range of built-in functions that cover various aspects of programming,
including mathematical operations, data type conversions, string manipulations, file handling,
input/output operations, and much more. These functions are designed to be intuitive, easy to
use, and optimized for performance.

Real life application:


• Data Manipulation and Analysis: Built-in functions like len(), max(), min(), sum(),
and sorted() are commonly used in data analysis tasks to calculate statistics, find the
length of data, sort values, or perform aggregations.

• Data Type Conversion: Functions like int(), float(), str(), and bool() are used to
convert data types. These conversions are often necessary when working with user
inputs, data validation, or data transformation.

Types of built-in function


###print(): The print() function in Python is a built-in function that outputs the specified values
or variables to the standard output (console). It converts the provided arguments into a textual
representation and displays them as output. The print() function is commonly used for
debugging, displaying information, or generating output for the user.

# Printing a multiple argument


name = "John"
age = 30
print("My name is", name, "and I am", age, "years old.")

# output: My name is John and I am 30 years old.

# Using the sep argument to specify the separator between arguments


fruit = "apple"
color = "red"
print(fruit, color, sep="-")
# output: apple-red

sorted():
The sorted() function in Python is a built-in function that returns a new sorted list from the
elements of the provided iterable. It takes an iterable as an argument and arranges its elements
in ascending order (by default) or based on a custom sorting criteria. The original iterable is not
modified, and the sorted list is returned as the result. ```python # Sort a list of strings in
ascending order fruits = ["banana", "apple", "orange", "pear"] sorted_fruits = sorted(fruits)
print(sorted_fruits)

Output: ['apple', 'banana', 'orange', 'pear']

Sort a list of strings in descending order


sorted_fruits_desc = sorted(fruits, reverse=True) print(sorted_fruits_desc)
Output: ['pear', 'orange', 'banana', 'apple']
### len():
The len() function in Python is a built-in function that returns the
length of an object. It takes an object as an argument and evaluates
the object to determine its length. The returned value is an integer
representing the number of items, characters, or elements in the
object.

```python
# Finding the number of characters
name = "John"
print(len(name))
# output: 4

type():
The type() function in Python is a built-in function that returns the data type of an object. It takes
one argument and evaluates the object to determine its type. The returned value is a type object
that represents the specific category or class to which the object belongs.

# Finding the data type


name = "John"
age = 30
print(type(name))
# Output: <class 'str'>
print(type(age))
# Output: <class 'int'>

range():
The range() function in Python is a built-in function that generates a sequence of numbers within
a specified range. It takes up to three arguments and returns a range object that represents the
sequence of numbers. The range object can be used in loops or converted to other iterable
objects, such as lists or tuples, to access the individual elements. Example:

# Printing numbers in a specified range


for num in range(1, 6):
print(num, end=" ")
# output: 1 2 3 4 5

input():
The input() function in Python is a built-in function used to accept user input from the keyboard.
It prompts the user with a message, waits for the user to enter input, and returns the entered
value as a string. The input() function allows for interactive input, enabling user interaction and
data entry during the execution of a program.
# Printing the name John
name = input("What is your name?")
print("Hello, " + name)
# Ouput: Hello, John

max():
The max() function in Python is a built-in function that returns the largest value from a sequence
of values or a collection. It takes one or more arguments and evaluates them to find the
maximum value. The returned value represents the maximum value found among the provided
arguments.

# Finding the biggest value in the list


numbers = [5, 2, 8, 1, 9, 4]
max_number = max(numbers)
print("The maximum number is:", max_number)
# Output: 9

min():
The min() function in Python is a built-in function that returns the smallest value from a
sequence of values or a collection. It takes one or more arguments and evaluates them to find
the minimum value. The returned value represents the smallest value found among the provided
arguments.

# Finding the smallest value


numbers = [5, 2, 8, 1, 9, 4]
min_number = min(numbers)
print("The minimum number is:", min_number)
# Output: 1

sum():
The sum() function in Python is a built-in function that returns the sum of all the elements in an
iterable. It takes an iterable as an argument and iterates over its elements, accumulating the
values and returning the total sum. The iterable can contain numeric values, such as integers or
floats, or other objects that support addition.

# Finding the sum value


numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
# Output: 15

Type Casting in Python using different built-in function:


In Python, type casting refers to the process of converting the data type of an object or variable
to a different data type. It allows you to explicitly specify the desired data type for an object.
Type casting is achieved by using various built-in functions, such as int(), float(), str(), list(), and
bool(). These functions take an object as input and return a new object of the specified data type.

• Integer Casting:

Integer Casting in Python is the process of converting a value or object of a different data type,
such as a string or float, into an integer. It allows you to explicitly specify that you want the value
to be treated as an integer by using the int() function. This function examines the input value and
creates a new object that represents the whole number without any decimal places.

# Float to Integer
float_num = 3.14
int_num = int(float_num)
print(int_num)
# Output: 3

# String to Integer
str_num = "42"
int_num = int(str_num)
print(int_num)
# Output: 42

• Float Casting:

Float casting in Python refers to the process of converting a value or object of another data type,
such as an integer or string, into a floating-point number. It involves using the float() built-in
function to explicitly specify the desired data type as a float. The function analyzes the input
value and produces a new object that represents a decimal number with a fractional component,
if applicable. Essentially, float casting allows you to convert non-floating-point values into their
corresponding floating-point representations, enabling calculations and operations involving
decimal numbers.

# Integer to Float
int_num = 42
float_num = float(int_num)
print(float_num)
# Output: 42.0

# String to Float
str_num = "3.14"
float_num = float(str_num)
print(float_num)
# Output: 3.14

• String Casting:

String casting in Python refers to the process of converting a value or object of another data
type, such as an integer or float, into a string. It allows you to explicitly specify that you want the
value to be represented as a string by using the str() function. This function takes the input value
and creates a new object that represents it as a sequence of characters enclosed within
quotation marks. In simpler terms, string casting converts a non-string value into a textual
representation that can be manipulated and displayed as a string.

# Integer to String
int_num = 42
str_num = str(int_num)
print(str_num)
# Output: "42"

# Float to String
float_num = 3.14
str_num = str(float_num)
print(str_num)
# Output: "3.14"

• Boolean Casting:

Boolean casting in Python refers to the process of converting a value or object of another data
type into a boolean value. It involves using the bool() built-in function to explicitly specify the
desired data type as a boolean. The function examines the input value and produces a new
object that represents either True or False based on certain rules. Boolean casting is particularly
useful when you need to evaluate conditions or perform logical operations that require a
boolean value. It allows you to convert different data types into their corresponding boolean
representations, enabling effective boolean logic and decision-making in your code.

# Integer to Boolean
int_num = 1
bool_val = bool(int_num)
print(bool_val)
# Output: True

# String to Boolean
str_val = "True"
bool_val = bool(str_val)
print(bool_val)
# Output: True

User defined function


In Python, a user-defined function is a function that is created by the user themselves. It is a self-
contained block of code that performs a particular task and can be reused multiple times
throughout the program. The user can define the function with a specific name, input
parameters, and the block of code that accomplishes the task. After defining the function, it can
be called from any part of the program by using its name and passing arguments as required.
Using user-defined functions is a useful technique to organize and reuse code in larger
programs, which can increase code readability and maintainability.
Syntax:
def function_name(parameter1, parameter2, ...):
"""
Function docstring (optional)
"""
# Function body/block
statement1
statement2
...
return expression

• Function Header/Declaration: Starts with the def keyword, followed by the function
name and a pair of parentheses. The parentheses may contain parameters separated
by commas. Parameters are optional and can be omitted if the function doesn't
require any inputs.

• Function Name: The name assigned to the function, which should follow Python's
naming conventions. It should be descriptive and indicative of the function's
purpose.

• Parameters: Optional inputs to the function enclosed within the parentheses.


Parameters act as placeholders for the values passed to the function when it is
called. You can have zero or more parameters, separated by commas.

• Function Docstring (optional): A multiline string enclosed within triple quotes ("""
"""), immediately after the function header. It provides documentation or a brief
description of the function's purpose, parameters, and return values. Although
optional, docstrings are highly recommended for documenting your functions.

• Function Body/Block: Consists of the indented set of statements that make up the
function's functionality. These statements are executed when the function is called.
The indentation level defines the scope of the function body.

• Statements: The code statements or instructions that define the operations and
computations performed by the function. These statements can include
assignments, conditionals, loops, function calls, and more.

• Return Statement: Optional statement that specifies the value or values to be


returned as the function's result. It is used to exit the function and send the result
back to the caller. If omitted, the function returns None by default.

# Creating a function named add_numbers


def add_numbers(x, y):
sum = x + y
return sum
result = add_numbers(5, 7)
print(result)
# Output: 12
# Creating a functions to calculate the string length
def string_length(input_string):
length = len(input_string)
return length
result = string_length("Hello, World!")
print(result)
# Output: 13

Arguments in Function
In Python, function arguments are the values or variables that are passed to a function when it is
called or invoked. They provide a way to pass data or information into a function so that it can
perform a specific task or computation using that data.

Python supports several types of function arguments, including:


Positional arguments: Positional arguments in Python are a method of passing arguments to a
function based on their position or order. When using positional arguments, the arguments are
matched with function parameters by their position in the function call. The first argument
corresponds to the first parameter, the second argument to the second parameter, and so on.
Positional arguments are assigned to function parameters based on their order of appearance.

Syntax

function_name(arg1, arg2, arg3, ...)

In this syntax, arg1, arg2, arg3, and so on represent the arguments being passed to the function.
The order in which the arguments are passed determines the corresponding parameter
assignments within the function.

# Creating a function for personalized messages


def greet_user(name, message):
print(f"Hello, {name}! {message}")
greet_user("Alice", "How are you doing today?")
greet_user("Bob", "It's nice to see you again.")
# output:Hello, Alice! How are you doing today?
#Hello, Bob! It's nice to see you again.

def calculate_discounted_price(original_price, discount_percentage):


discount_amount = original_price * (discount_percentage / 100)
discounted_price = original_price - discount_amount
return discounted_price

item_price = 100
discount = 20

final_price = calculate_discounted_price(item_price, discount)


print("The final price after a", discount, "% discount is $",
final_price, ".")
# output:The final price after a 20 % discount is $ 80.0 .

Keyword arguments: These are arguments that are passed to a function using their
corresponding parameter names. Keyword arguments are useful when calling a function with
many parameters, as they allow you to specify which parameter each value corresponds to.

Syntax:

function_name(parameter1=value1, parameter2=value2, ...)

• parameter1, parameter2, and so on represent the parameters of the function.


• value1, value2, and so on represent the corresponding values to be assigned to the
parameters.
• The parameters and values are separated by an equal sign (=).
• The order of the keyword arguments does not matter, as they are explicitly assigned
based on their parameter names.
# Function to Describe a Pet
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='dog', pet_name='fido')
describe_pet(pet_name='mittens', animal_type='cat')
# output:
I have a dog.
My dog's name is Fido.
I have a cat.
My cat's name is Mittens.

#Creating Student Records


def create_student(name, age, **kwargs):
student = {
'name': name,
'age': age,
'courses': kwargs.get('courses', []),
'major': kwargs.get('major', 'Undeclared')
}
return student

student1 = create_student(name="John", age=20, major="Computer


Science")
student2 = create_student(name="Jane", age=22, courses=["Math",
"Physics"])

print(student1)
print(student2)

#output: {'name': 'John', 'age': 20, 'courses': [], 'major': 'Computer


Science'}
#output: {'name': 'Jane', 'age': 22, 'courses': ['Math', 'Physics'],
'major': 'Undeclared'}

Default arguments: Default arguments in Python allow for providing default values for function
parameters. When defining a function, you can assign a default value to a parameter, making it
optional during function call. If no value is provided for a default argument, the default value is
used as the parameter's value.

Syntax:

def function_name(parameter1=default_value1,
parameter2=default_value2, ...):
# Function body
...

In this syntax, default_value1, default_value2, and so on represent the default values assigned to
the respective parameters. If a value is not provided for these parameters during function call,
the default values are used.

# Function to describe our pet


def describe_person(name, age=30):
print(f"{name.title()} is {age} years old.")
describe_person("Alice")
describe_person("Bob", 25)
# output:Alice is 30 years old.
# output:Bob is 25 years old.

#Calculating Total Bill Amount with Discount and Tax


def calculate_total_bill(amount, discount=0, tax_rate=0):
discounted_amount = amount - (amount * discount / 100)
tax_amount = discounted_amount * tax_rate / 100
total_bill = discounted_amount + tax_amount
return total_bill

bill1 = calculate_total_bill(1000)
bill2 = calculate_total_bill(1500, discount=10)
bill3 = calculate_total_bill(2000, discount=5, tax_rate=8)

print("Bill 1:", bill1)


print("Bill 2:", bill2)
print("Bill 3:", bill3)
# Output:- Bill 1: 1000.0
# Output:-Bill 2: 1350.0
# Output:-Bill 3: 2160.0

Variable-length arguments: Variable-length arguments in Python refer to the ability of a


function to accept a varying number of arguments. With variable-length arguments, a function
can handle different numbers of arguments, including none, one, or multiple arguments. This
provides flexibility and allows for more versatile function calls.

• *args is used to pass a variable number of positional arguments to a function.

Syntax:

def function_name(*args):
# Function body
...

• The asterisk (*) before the parameter name args indicates that the function can accept
any number of arguments, including zero, one, or multiple arguments.
• When calling a function with variable-length arguments, you can pass any number of
arguments separated by commas.
• Inside the function body, the args parameter behaves like a tuple that contains all the
passed arguments.
• You can iterate over the args tuple, access individual arguments using indexing, or
perform other operations as needed.
# Summing Variable-Length Numbers in Python
def sum_numbers(*numbers):
result = 0
for num in numbers:
result += num
return result
result1 = sum_numbers(1, 2, 3)
result2 = sum_numbers(4, 5, 6, 7, 8)
result3 = sum_numbers(9, 10)
# output:6
# output:30
# output:19

• **kwargs is used to pass a variable number of keyword arguments to a function.

Syntax:

def function_name(**kwargs):
# Function body
...

• The two asterisks (**) before the parameter name kwargs indicate that the function can
accept any number of keyword arguments.
• When calling a function with kwargs, you can pass keyword arguments using the
key=value syntax.
• Inside the function body, the kwargs parameter behaves like a dictionary, where the keys
are the argument names and the values are the corresponding argument values.
• You can access the keyword arguments by their keys, iterate over the keys and values, or
perform other dictionary operations as needed.
# Describing Person Attributes using Keyword Arguments
def describe_person(**kwargs):
for key, value in kwargs.items():
print(f"{key.capitalize()}: {value}")
describe_person(name="Alice", age=25, occupation="Engineer")
describe_person(name="Bob", location="New York")
# Output:Name: Alice
# Output:Age: 25
# Ouput: Occupation: Engineer
# Ouput: Name: Bob
# Ouput: Location: New York

# Calculating Weighted and Unweighted Averages


def calculate_average(*args, **kwargs):
weights = kwargs.get('weights', None)
if weights:
if len(args) != len(weights):
raise ValueError("Number of values and weights must be
equal.")
weighted_sum = sum(value * weight for value, weight in
zip(args, weights))
total_weight = sum(weights)
average = weighted_sum / total_weight
else:
average = sum(args) / len(args)
return average

# Example 1: Calculating average without weights


average1 = calculate_average(4, 5, 6, 7, 8)
print("Average 1:", average1)

# Example 2: Calculating average with weights


values = [4, 5, 6, 7, 8]
weights = [0.1, 0.2, 0.3, 0.2, 0.2]
average2 = calculate_average(*values, weights=weights)
print("Average 2:", average2)

# output:Average 1: 6.0
# output: Average 2: 6.1

Difference between Arguments and Parameters


• A parameter is a variable defined in a function definition. It represents a value that
must be passed into the function when it is called. Parameters are also sometimes
called formal parameters or formal arguments.
• An argument is the actual value that is passed into a function when it is called. It is
the value that is assigned to the parameter variable in the function definition.
Arguments are sometimes called actual parameters or actual arguments.

def add_numbers(x, y): # x and y are parameters


result = x + y
return result

a = 5
b = 3
print(add_numbers(a, b)) # a and b are arguments
# output: 8

• x and y are the parameters of the add_numbers() function. When the function is called
with the arguments a and b, a is assigned to x and b is assigned to y. The function then
returns the result of adding x and y, which is 8.

Recursion
Recursion in Python is a technique where a function calls itself in order to solve a problem. It
involves breaking a problem down into smaller subproblems that are similar in structure to the
original problem, and then solving these subproblems recursively. Recursion can be a powerful
tool for solving problems that can be expressed in terms of smaller versions of themselves, and
it is commonly used in a variety of algorithms and data structures. When a function calls itself, it
creates a new instance of that function with its own set of variables and parameters. This new
instance can then call itself again, creating another new instance, and so on. The process
continues until a base case is reached, which is a problem that can be solved without further
recursion. Once the base case is reached, the function returns a value to the previous instance of
itself, which can then use that value to continue its own computation. Eventually, all the
instances of the function return their values and the original problem is solved.

Real life application of Python Recursion:


1. File System Operations: Recursion is useful for performing operations on file
systems that are structured as directories and subdirectories. It can be used to
search for files, traverse directory structures, calculate directory sizes, and perform
other file-related tasks.

2. Dynamic Programming: Recursive algorithms are often used in dynamic


programming to solve optimization problems by breaking them down into
overlapping subproblems. This technique allows for efficient computation of
solutions by reusing previously computed results.

3. Divide and Conquer Algorithms: Many divide and conquer algorithms, such as
merge sort and quicksort, utilize recursion to solve problems by breaking them
down into smaller subproblems. The solutions to the subproblems are then
combined to obtain the final result.
Syntax:
def recursive_function(parameters):
if base_case_condition:
# Base case: return a value or perform a terminating action
else:
# Recursive case: call the function recursively with modified
parameters
recursive_function(modified_parameters)

• recursive_function is the name of the function. It can be any valid function name.
• parameters represents the input values or arguments required for the function.
• base_case_condition is a condition that determines when the recursion should
terminate. It is the base case that defines the simplest form of the problem that can be
directly solved.
• The base case typically includes a return statement to provide the result or perform a
terminating action.
• In the recursive case, the function calls itself with modified parameters to solve a smaller
subproblem. The goal is to simplify the problem with each recursive call until the base
case is reached.
# Calculating Factorial using Recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(0)) # Output: 1
print(factorial(5)) # Output: 120
print(factorial(10)) # Output: 3628800
# Output: 1
# Output: 120
# Output: 3628800

Explanation:
• The factorial function takes a single argument n, which is the number we want to
calculate the factorial of.
• If n is equal to 0, the function returns 1. This is the base case of the recursion.
• If n is not 0, the function calculates the factorial of n-1 by calling itself with n-1 as the
argument.
• The function multiplies the result of the recursive call by n to get the factorial of n.
• The function returns the final result of the factorial calculation. When the function is
called with a value of n, it breaks the problem down into smaller subproblems by calling
itself with n-1.
• This process continues until the base case is reached (i.e., n equals 0).
• Once the base case is reached, the function returns 1 to the previous instance of itself,
which multiplies it by n and returns the result to the previous instance.
• This process continues until the original instance of the function returns the final result.
# Calculating Exponential Power using Recursion
def power(base, exponent):
if exponent < 0:
raise ValueError("Exponent must be a non-negative integer.")
if exponent == 0:
return 1
if exponent == 1:
return base
return base * power(base, exponent - 1)

# Calculate 2 raised to the power of 5


result = power(2, 5)
print("2 raised to the power of 5:", result)
#output: 2 raised to the power of 5: 32

Explanation:
• The power function is defined with two parameters: base and exponent.
• The function checks if the exponent is less than 0. If it is, it raises a ValueError with the
message "Exponent must be a non-negative integer."
• Next, the function checks if the exponent is equal to 0. If it is, the function returns 1, as
any number raised to the power of 0 is always 1.
• Then, the function checks if the exponent is equal to 1. If it is, the function returns the
base itself since any number raised to the power of 1 is equal to the base number.
• If none of the above conditions are met, the function recursively calls itself with base and
exponent - 1 as arguments. This reduces the exponent by 1 with each recursive call.
• The function multiplies the base with the result of the recursive call to obtain the final
result.
• The example result = power(2, 5) calculates 2 raised to the power of 5 using the power
function.
• The calculated result is stored in the result variable.
• Finally, the value of result is printed as "2 raised to the power of 5: 32".

Lambda Function
Lambda function is a small, anonymous function that can have any number of arguments, but
can only have one expression. It is a way to create a function without giving it a proper name,
hence the term "anonymous". Lambda functions are useful when we need to write a small
function for a specific purpose, and we don't want to define a named function for it.

Real life application:


1. Sorting and Ordering: Lambda functions are often used as key functions in sorting
algorithms or methods. They allow for custom sorting criteria by defining the
desired property or attribute to use as the basis for sorting. This is particularly
useful when sorting complex objects or datasets based on specific attributes or
properties.
2. API Development: In web development and API design, lambda functions can be
used to define small, disposable functions to handle specific API endpoints or route
handlers. This allows for concise code organization and reduces the need for
defining separate named functions for each route or endpoint.

3. Data Transformations: In data processing and analysis tasks, lambda functions are
useful for transforming data on the fly. They can be applied to individual elements of
a dataset or used with functions like map() and filter() to perform complex data
manipulations, filtering, or calculations.

Syntax:
lambda parameters: expression

Components of the Lambda function:

• lambda keyword: The lambda keyword is used to define a lambda function.

• Parameters: The parameters are the inputs to the lambda function. They are defined
after the lambda keyword, separated by commas. Lambda functions can have any
number of parameters, including zero or multiple parameters.

• Colon (:): The colon serves as a separator between the parameters and the function
body.

• Expression: The expression is the single line of code that represents the operation
or computation performed by the lambda function. It is written after the colon and
serves as the return value of the lambda function.

# Creating a lambda function to add value with 10.


x = lambda a : a + 10
print(x(5))
# output: 15

# Having multi-parameter Lambda function


add = lambda x, y: x + y
print(add(2, 3))
# Output: 5

# Sorting a list of dictionaries based on a specific key


students = [
{'name': 'John', 'age': 20},
{'name': 'Emily', 'age': 19},
{'name': 'Michael', 'age': 21},
{'name': 'Sophia', 'age': 20},
{'name': 'Daniel', 'age': 19}
]
sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)
# output: [{'name': 'Emily', 'age': 19}, {'name': 'Daniel', 'age':
19}, {'name': 'John', 'age': 20}, {'name': 'Sophia', 'age': 20},
{'name': 'Michael', 'age': 21}]

Remember:
• This function can have any number of arguments but only one expression, which is
evaluated and returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
• It has various uses in particular fields of programming, besides other types of
expressions in functions.

Map fucntion
The map() function in Python applies a given function to each item of an iterable and returns an
iterator that yields the results. It takes two or more arguments: the function to be applied and
one or more iterables. The function is applied to each element of the iterables in a "one-to-one"
correspondence.

Real life application:


1. Data Cleaning and Preprocessing: In data cleaning and preprocessing tasks, the
map() function can be used to clean and standardize data. It allows you to apply
cleaning functions or transformations to each element of a dataset, removing or
replacing invalid or missing values, converting data types, or standardizing formats.

2. Feature Engineering: Feature engineering involves creating new features or


modifying existing ones in a dataset to improve machine learning models'
performance. The map() function is used to apply feature engineering operations to
each element of a feature column, such as encoding categorical variables,
transforming numerical data, or generating new derived features.

3. Text Processing: The map() function is handy for text processing tasks, such as
tokenization, stemming, or lemmatization. It allows you to apply text processing
functions to each word or sentence in a text document, enabling you to perform
various natural language processing (NLP) tasks.

Syntax:
map(fun, iter)

• function is the function to be applied to each item of the iterables. It can be a built-in
function, a lambda function, or a user-defined function.
• iterable1, iterable2, and so on are one or more iterables (e.g., lists, tuples, strings) that
will be iterated over simultaneously. The function is applied to the corresponding items
of the iterables.
# use of map function to square values
numbers = [1, 2, 3, 4, 5]
def square(x):
return x ** 2
squared_numbers = map(square, numbers)
print(list(squared_numbers))
# Output:[1, 4, 9, 16, 25]

# Double all numbers using map and lambda


numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
# Output: [2, 4, 6, 8]

# Capitalize strings using map function


words_list = ["hello", "world", "how", "are", "you"]
def capitalize_first_letter(word):
return word.capitalize()
capitalized_list = list(map(capitalize_first_letter, words_list))
print(capitalized_list)
# Output:['Hello', 'World', 'How', 'Are', 'You']

Filter Function
filter() function in Python is used to filter out elements from a sequence that do not satisfy a
certain condition. It takes two arguments: a function that defines the condition and a sequence
to apply the function to. The function returns a filter object that can be converted into a list or a
tuple.

Real life application:

1. Data Analysis and Exploratory Data Analysis (EDA): The filter() function is useful in
exploratory data analysis tasks to selectively analyze specific subsets of data. It
allows you to filter data based on certain attributes, such as filtering a sales dataset
to analyze performance by region or filtering a customer dataset to analyze
customer behavior based on demographic criteria.

2. Data Visualization: In data visualization, the filter() function can be utilized to


selectively visualize subsets of data. It enables you to filter data based on specific
conditions or attributes, allowing for more focused and insightful visualizations. For
example, you can filter and visualize data points that meet certain criteria to identify
patterns or outliers more easily.

3. Event Filtering: In event-driven programming or systems, the filter() function can


be used to filter events based on specific criteria. It allows you to selectively handle
or process events that meet certain conditions while ignoring others. This is
commonly used in event-driven frameworks or systems that require handling
multiple events concurrently.
Syntax:
filter(function, sequence)

• function: The filtering function is applied to each element of the iterable. It evaluates the
element and returns True or False based on the filtering criterion. Elements for which the
function returns True are included in the resulting iterator.
• iterable: The iterable represents the sequence of elements that will be filtered. It can be a
list, tuple, string, or any other iterable object.
# Finding the even number
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(number):
return number % 2 == 0
filtered_numbers = list(filter(is_even, numbers))
print(filtered_numbers) # Output: [2, 4, 6, 8, 10]

# Filtering Students with Name Alice


students = [ {"name": "Alice", "age": 20}, {"name": "Bob",
"age": 25}, {"name": "Charlie", "age": 30}, {"name": "Dave",
"age": 35},]

def has_name_Alice(student):
return student["name"] == "Alice"

alice_students = list(filter(has_name_Alice, students))


print(alice_students)
# Output:[{'name': 'Alice', 'age': 20}]

Reduce Function
The reduce() function in Python is a built-in function from the functools module that applies a
specified function to the elements of an iterable in a cumulative way. It repeatedly applies the
function to pairs of elements, reducing the iterable to a single value.

Real life application:


• Building Strings: In text processing, reduce could be used to concatenate a list of strings
into a single string.
• Computational Geometry: If you're dealing with objects in 2D or 3D space, you could use
reduce to calculate the center of mass of a group of objects, by summing their
coordinates and then dividing by the total number of objects.
• Data Aggregation: When working with data analysis or data science, you might use
reduce to aggregate data. For instance, you could have a list of tuples, where each tuple
contains the name of a city and its population. You could use reduce to find the total
population across all cities.
Syntax:
functools.reduce(function, iterable[, initializer])

• function: This is a function that takes two elements and returns a single value. For
example, a function that adds two numbers together or multiplies them.

• iterable: This is a sequence (string, tuple, etc.) or collection (set, dictionary, etc.) or
an iterator object to be reduced.

• initializer (optional): This is a value that is used as the initial argument to the
function. If the iterable is empty, the initializer is returned instead. If the initializer is
not given and the iterable contains only one item, the first item is returned.

# Building a ProductReducer
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)

print(product)
# Output: 120

# Concatenating Strings with Reduce


from functools import reduce

strings = ["hello", "world", "how", "are", "you"]


concatenated_string = reduce(lambda x, y: x + " " + y, strings)
print(concatenated_string)
# Output: hello world how are you

# Calculating Total Price of Books


from functools import reduce
books = [
{"title": "Book 1", "price": 19.99},
{"title": "Book 2", "price": 29.99},
{"title": "Book 3", "price": 14.99},
{"title": "Book 4", "price": 24.99},
]
total_price = reduce(lambda acc, book: acc + book['price'], books, 0)
print(total_price)
# output: 89.96

#Key Takeaways

• This chapter has provided an introduction to Python Functions and types of functions
its relevance in the field of python & data science. Functions A function is a block of
reusable code that performs a specific task. Functions provide modularity and code
reusability, allowing you to break down complex tasks into smaller, manageable
pieces.
• Furthermore, this chapter has Functions are important because they allow Functions
are used in various programming tasks, such as data processing, algorithm
implementation, user interface design, and more. They help in organizing code,
improving code readability, and making it easier to maintain and update.

• The chapter has also covered Types of functions and one line function lambda
fucntion,map function, reduce function.

• Finally, the chapter has provided a summary of the topics covered in the class.
Understanding Understanding functions and their types is crucial for writing modular
and efficient code in Python. They help in organizing code, promoting code reuse, and
making programs more flexible and scalable.

• Overall, this chapter has provided a solid foundation for understanding functions and
its types in the field of python & data science. Understanding the Python functions and
apllication in Python is essential for any data science professional.

You might also like