0% found this document useful (0 votes)
4 views20 pages

Unit 3 Notes Python

This document provides an overview of functions in Python, including their declaration, types, and benefits such as increased code readability and reusability. It covers various aspects of functions, including parameters, arguments, recursion, and lambda functions, along with examples to illustrate their usage. Additionally, it discusses higher-order functions and the differences between lambda functions and traditional function definitions.

Uploaded by

Mayank
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Unit 3 Notes Python

This document provides an overview of functions in Python, including their declaration, types, and benefits such as increased code readability and reusability. It covers various aspects of functions, including parameters, arguments, recursion, and lambda functions, along with examples to illustrate their usage. Additionally, it discusses higher-order functions and the differences between lambda functions and traditional function definitions.

Uploaded by

Mayank
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3

Functions in python

Python function is a block of statements that return the specific task. The
idea is to put some commonly or repeatedly done tasks together and make
a function so that instead of writing the same code again and again for
different inputs, we can do the function calls to reuse code contained in it
over and over again.
Some Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability

Python Function Declaration


The syntax to declare a function is:

Types of Functions in Python


Below are the different types of functions in python:
• Built-in library function: These are standard Python that are
available to use.
• User-defined function: We can create our own functions based on
our requirements.
Creating a Function in Python
• We can define a function in Python, using the def keyword. We can
add any type of functionalities and properties to it as we require. By
the following example, we can understand how to write a function in
Python. In this way we can create Python function definition by using
def keyword.
# A simple Python function
def fun():
print("Welcome to GFG")

Calling a Function in Python


After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular function. Below is the example for calling def function Python.

# A simple Python function


def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()

Python Function with Parameters


If you have experience in C/C++ or Java then you must be thinking about
the return type of the function and data type of arguments. That is possible
in Python as well (specifically for Python 3.5 and above).

Python Function Syntax with Parameters

def function_name(parameter: data_type) -> return_type:


"""Docstring"""
# body of the function
return expression

def add(num1: int, num2: int) -> int:


"""Add two numbers"""
num3 = num1 + num2

return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output-

The addition of 5 and 15 results 20.

# some more functions


def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))

Output-
False True

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether
the number passed as an argument to the function is even or odd.

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Output:

Even
Odd
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time
of the function call. In Python, we have the following function argument
types in Python:
• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments *args and
**kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument. The following example
illustrates Default arguments to write functions in Python.

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

Output:
x: 10
y: 50

Like C++ default arguments, any number of arguments in a function can


have a default value. But once we have a default argument, all the
arguments to its right must also have default values.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so
that the caller does not need to remember the order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Ayush', lastname='Singh’)
student(lastname='Singh’, firstname='Ayush’))
Output:
Ayush Singh
Ayush Singh

Positional Arguments
We used the position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or
value) is assigned to age. By changing the position, or if you forget the order
of the positions, the values can be used in the wrong places, as shown in
the Case-2 example below, where 27 is assigned to the name and Suraj is
assigned to the age.

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword/Variable length Arguments


In Python Arbitrary Keyword Arguments, *args and **kwargs can pass a
variable number of arguments to a function using special symbols. There
are two special symbols:
• *args in Python (Non-Keyword Arguments)
• **kwargs in Python (Keyword Arguments)

Example 1: Variable length non-keywords argument

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'python’)

Output:

Hello
Welcome
to
Python

Example 2: Variable length keyword arguments

# Python program to illustrate


# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in [Link]():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

Output:
first == Geeks
mid == for
last == Geeks

Docstring
The first string after the function is called the Document string
or docstring in short. This is used to describe the functionality of the
function. The use of docstring in functions is optional but it is considered a
good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)

# A simple Python function to check


# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


print(evenOdd.__doc__)

Output:
Function to check if the number is even or odd

Python Function within Functions


A function that is defined inside another function is known as the inner
function or nested function. Nested functions can access variables of the
enclosing scope. Inner functions are used so that they can be protected from
everything happening outside the function.
# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = 'I love python’

def f2():
print(s)

f2()

# Driver's code
f1()

Output:
I love python

Anonymous Functions in Python


In Python, an anonymous function means that a function is without a name.
As we already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions.

# Python code to illustrate the cube of a number


# using lambda function
def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

Output:
343
343

Recursive Functions in Python


Recursion in Python refers to when a function calls itself. There are many
instances when you have to build a recursive function to solve Mathematical
and Recursive Problems.
Using a recursive function should be done with caution, as a recursive
function can become like a non-terminating loop. It is better to check your exit
statement while creating a recursive function.

Wap to find factorial of a number using recursion

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

Output:
24

Return Statement in Python Function


The function return statement is used to exit from a function and go back to
the function caller and return the specified value or data item to the
caller. The syntax for the return statement is:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant
which is returned at the end of the function execution. If none of the above
is present with the return statement a None object is returned.
Example: Python Function Return Statement

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))
Output:
4
16

Pass by Reference and Pass by Value


One important thing to note is, in Python every variable name is a reference.
When we pass a variable to a function Python, a new reference to the
object is created. Parameter passing in Python is the same as reference
passing in Java.

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output:
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to something


else, the connection between the passed and received parameters is broken.
For example, consider the below program as follows:

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]
# Driver Code (Note that lst is not modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output:
[10, 11, 12, 13, 14, 15]

Another example demonstrates that the reference link is broken if we assign


a new value (inside the function).

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = 20

# Driver Code (Note that x is not modified


# after function call.
x = 10
myFun(x)
print(x)

Output:
10

Python lambda functions

Python Lambda Functions are anonymous functions means that the


function is without a name. As we already know the def keyword is used to
define a normal function in Python. Similarly, the lambda keyword is used to
define an anonymous function in Python.
In the example, we defined a lambda function(upper) to convert a string to
its upper case using upper().
s = 'Ayush’

upper = lambda string: [Link]()


print(upper(s))

Output:
AYUSH

This code defines a lambda function named upper that takes a string as its
argument and converts it to uppercase using the upper() method. It then
applies this lambda function to the string ‘GeeksforGeeks’ and prints the
result

Python Lambda Function Syntax


Syntax: lambda arguments : expression
• 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.

Use of Lambda Function in Python


Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function
Here, the ‘format_numric’ calls the lambda function, and the num is passed
as a parameter to perform operation

format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"

print("Int formatting:", format_numeric(1000000))


print("float formatting:", format_numeric(999999.789541235))

Int formatting: 1.000000e+06


float formatting: 999,999.79
Difference Between Lambda functions and def defined function
The code defines a cube function using both the ‘def' keyword and a
lambda function. It calculates the cube of a given number (5 in this case)
using both approaches and prints the results. The output is 125 for both
the ‘def' and lambda functions, demonstrating that they achieve the same
cube calculation.

def cube(y):
return y*y*y

lambda_cube = lambda y: y*y*y


print("Using function defined with `def` keyword, cube:", cube(5))
print("Using lambda function, cube:", lambda_cube(5))

Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125

As we can see in the above example, both the cube() function


and lambda_cube()function behave the same and as intended. Let’s analyze
the above example a bit more:

With lambda function Without lambda function

Supports single-line sometimes Supports any number of lines inside


statements that return some value. a function block

Good for performing short Good for any cases that require
operations/data manipulations. multiple lines of code.

Using the lambda function can


We can use comments and function
sometime reduce the readability of
descriptions for easy readability
code.

Practical Uses of Python lambda function


Python Lambda Function with List Comprehension
On each iteration inside the list comprehension, we are creating a new
lambda function with a default argument of x (where x is the current item in
the iteration). Later, inside the for loop, we are calling the same function
object having the default argument using item() and get the desired value.
Thus, is_even_list stores the list of lambda function objects.

is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]


for item in is_even_list:
print(item())

Output:
10
20
30
40

Python Lambda Function with if-else


Here we are using the Max lambda function to find the maximum of two
integers.

Max = lambda a, b : a if(a > b) else b


print(Max(1, 2))

Output:
2

Python Lambda with Multiple Statements


Lambda functions do not allow multiple statements, however, we can
create two lambda functions and then call the other lambda function as a
parameter to the first function. Let’s try to find the second maximum
element using lambda.
The code defines a list of sublists called ‘List'. It uses lambda functions to
sort each sublist and find the second-largest element in each sublist. The
result is a list of second-largest elements, which is then printed. The output
displays the second-largest element from each sublist in the original list.

a = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]


sortList = lambda x: (sorted(i) for i in x)
secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(a, sortList)

print(res)

Output
[3, 16, 9]

Lambda functions can be used along with built-in functions like filter
() map() and reduce ().

Higher order functions:


A function is called
Higher Order Function
if it contains other functions as a parameter or returns a function as an
output i.e, the functions that operate with another function are known as
Higher order Functions. It is worth knowing that this higher order function is
applicable for functions and methods as well that takes functions as a
parameter or returns a function as a result. Python too supports the
concepts of higher order functions.
Properties of higher-order functions:
• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables, lists, …
Functions as objects
In Python, a function can be assigned to a variable. This assignment does
not call the function, instead a reference to that function is created. Consider
the below example, for better understanding.
Example:
# Python program to illustrate functions
# can be treated as objects
def shout(text):
return [Link]()
print(shout('Hello'))

# Assigning function to a variable


yell = shout

print(yell('Hello'))

Output:
HELLO
HELLO

In the above example, a function object referenced by shout and creates a


second name pointing to it, yell.
Passing Function as an argument to other function
Functions are like objects in Python, therefore, they can be passed as
argument to other functions. Consider the below example, where we have
created a function greet which takes a function as an argument.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return [Link]()

def whisper(text):
return [Link]()

def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function \
passed as an argument.")
print(greeting)

greet(shout)
greet(whisper)

Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
Returning function
As functions are objects, we can also return a function from another
function. In the below example, the create_adder function returns adder
function.
Example:
# Python program to illustrate functions
# Functions can return another function

def create_adder(x):
def adder(y):
return x + y

return adder

add_15 = create_adder(15)

print(add_15(10))

Output:
25

Decorators
Decorators are the most common use of higher-order functions in Python. It
allows programmers to modify the behavior of function or class. Decorators
allow us to wrap another function in order to extend the behavior of
wrapped function, without permanently modifying it. In Decorators,
functions are taken as the argument into another function and then called
inside the wrapper function.
Syntax:
@gfg_decorator
def hello_decorator():
.
.
.

The above code is equivalent to –

def hello_decorator():
.
.
.

hello_decorator = gfg_decorator(hello_decorator)
In the above code,
gfg_decorator
is a callable function, will add some code on the top of some another
callable function,
hello_decorator
function and return the wrapper function.

Map Reduce and Filter Operations in Python


Below, are examples of Map Reduce and Filter Operations in Python:
• map() Function
• Reduce() Function
• Filter() Function
Map Function in Python
The map () function returns a map object(which is an iterator) of the
results after applying the given function to each item of a given iterable
(list, tuple, etc.).
Syntax: map(fun, iter)
Parameters:
• fun: It is a function to which map passes each element of given
iterable.
• iter: iterable object to be mapped.

Example: In this example, Python program showcases the usage of


the mapfunction to double each number in a given list by applying
the double function to each element, and then printing the result as a list.

# Function to return double of n


def double(n):
return n * 2

# Using map to double all numbers


numbers = [5, 6, 7, 8]
result = map(double, numbers)
print(list(result))

Output
[10, 12, 14, 16]

Reduce Function in Python


The reduce function is used to apply a particular function passed in its
argument to all of the list elements mentioned in the sequence passed
[Link] function is defined in “functools” module.
Syntax: reduce(func, iterable[, initial])
Parameters:
• fun: It is a function to execuate on each element of the iterable
objec
• iter: It is iterable to be reduced

Example : In this example, we are using reduce() function from


the functoolsmodule to compute the product of elements in a given list by
continuously applying the lambda function that multiplies two numbers
together, resulting in the final product.

import functools

# Define a list of numbers


numbers = [1, 2, 3, 4]

# Use reduce to compute the product of list elements


product = [Link](lambda x, y: x * y, numbers)
print("Product of list elements:", product)

Output
Product of list elements: 24

Filter Function in Python


The filter() method filters the given sequence with the help of a function
that tests each element in the sequence to be true or not.
Syntax: filter(function, sequence)
Parameters:
• function: function that tests if each element of a sequence is true
or not.
• sequence: sequence which needs to be filtered, it can be sets, lists,
tuples, or containers of any iterators.
Example : In this example, we defines a function is_even to check whether
a number is even or not. Then, it applies the filter() function to a list of
numbers to extract only the even numbers, resulting in a list containing only
the even elements. Finally, it prints the list of even numbers.

# Define a function to check if a number is even


def is_even(n):
return n % 2 == 0

# Define a list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter to filter out even numbers


even_numbers = filter(is_even, numbers)
print("Even numbers:", list(even_numbers))

Output
Even numbers: [2, 4, 6, 8, 10]

You might also like