Functions
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.
• 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.
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.
• 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.
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)
```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.
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:
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.
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.
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.
• 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
• 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.
• 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.
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.
Syntax
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.
item_price = 100
discount = 20
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:
print(student1)
print(student2)
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.
bill1 = calculate_total_bill(1000)
bill2 = calculate_total_bill(1500, discount=10)
bill3 = calculate_total_bill(2000, discount=5, tax_rate=8)
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
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
# output:Average 1: 6.0
# output: Average 2: 6.1
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.
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)
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.
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
• 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.
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.
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]
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.
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.
• 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]
def has_name_Alice(student):
return student["name"] == "Alice"
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.
• 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
#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.