0% found this document useful (0 votes)
5 views14 pages

Section 2 Part 2 Functions Lecture 2

The document provides an overview of functions in Python programming, covering topics such as function definitions, types of function arguments, recursive functions, and functions with multiple return values. It includes examples and explanations of key concepts like default arguments and variable scope. The lecture aims to equip students with a modular programming approach using functions.

Uploaded by

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

Section 2 Part 2 Functions Lecture 2

The document provides an overview of functions in Python programming, covering topics such as function definitions, types of function arguments, recursive functions, and functions with multiple return values. It includes examples and explanations of key concepts like default arguments and variable scope. The lecture aims to equip students with a modular programming approach using functions.

Uploaded by

slimbookmacbook
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Functions

Python Programming

Dr. Vidula V. Meshram


[email protected]
Department of Computer Engineering

BRACT’S, Vishwakarma Institute of Technology, Pune

(An Autonomous Institute affiliated to Savitribai Phule Pune University)


(NBA and NAAC accredited, ISO 21001:2018 certified)

Department of Engineering Sciences and Humanities, VIT, Pune


FUNCTIONS (2Hrs)
❖ Function Definition and its types
❖ Function Calling
❖ Types of Function Arguments
❖ Anonymous Functions (Lambda Functions)
❖ Recursive Functions
❖ Function with more than one return value.
❖ Default value to parameter
❖ keyword parameter
❖ Scope of Variables

Lecture Outcome: Apply a modular programming approach by


making use of functions.
Department of Engineering Sciences and Humanities, VIT, Pune
Recursive Function
 A recursive function is a function that calls itself during its execution.
 This technique allows the function to solve a problem by breaking it down into smaller, more
manageable sub-problems, with each function call representing one of these sub-problems.
 Recursive functions are particularly useful for tasks that can be defined in terms of similar
subtasks, such as calculating the factorial of a number, traversing a tree, or solving the
Fibonacci sequence.

Key Concepts of Recursive Functions


1. Base Case: This is the condition that stops the recursion. Without a base case, the function
would call itself indefinitely, leading to a stack overflow error.
2. Recursive Case: This is where the function calls itself with a modified argument, moving closer
to the base case with each call.

Example: Factorial Calculation


The factorial of a non-negative integer n is the product of all positive integers less than or equal to
n. It's denoted as n!. The factorial of 0 is defined as 1. The recursive definition of factorial is:

• 0!=10! = 10!=1 (base case)


• n!=n×(n−1)!n! = n \times (n-1)!n!=n×(n−1)! for n>0n > 0n>0 (recursive case)

Department of Engineering Sciences and Humanities, VIT, Pune


Recursive Function
How It Works: When factorial(5) is called:
It checks if n is 0. Since n is 5, it proceeds to the
 Example :
def factorial(n): recursive case.
# Base case: if n is 0, the factorial is 1 It returns 5 * factorial(4).
if n == 0:
return 1 The factorial(4) call returns 4 * factorial(3).
else: This process continues until factorial(0) is reached,
# Recursive case: n *
factorial of (n-1) which returns 1 (the base case).
return n * factorial(n - 1) Then, the stack unwinds, and each multiplication

# Example usage is resolved:


print(factorial(5)) # Output: 120 factorial(1) returns 1 * 1 = 1
factorial(2) returns 2 * 1 = 2
factorial(3) returns 3 * 2 = 6
factorial(4) returns 4 * 6 = 24
factorial(5) returns 5 * 24 = 120
Department of Engineering Sciences and Humanities, VIT, Pune
Functions with Multiple Return Values
• In Python, a function can return multiple values by separating them with commas.
• These values are returned as a tuple, which can then be unpacked into separate
variables.
• Example:
def calculate_area_and_perimeter(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter

# Unpacking the returned tuple


area, perimeter = calculate_area_and_perimeter(5, 3)
print(f"Area: {area}, Perimeter: {perimeter}")

• This would produce following result:


Area: 15, Perimeter: 16

Department of Engineering Sciences and Humanities, VIT, Pune


Functions with Multiple Return Values
• Problem: Write a function that takes a list of numbers and returns both the sum
and the average of the numbers.
• Solution
def sum_and_average(numbers):
total = sum(numbers)
average = total / len(numbers)
return total, average

numbers = [1, 2, 3, 4, 5]
total, avg = sum_and_average(numbers)
print(f"Sum: {total}, Average: {avg}")

• This would produce following result:


Sum: 15, Average: 3.0

Department of Engineering Sciences and Humanities, VIT, Pune


Functions with Multiple Return Values
Example:
• Following is the example to show how lambda form of function works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

• This would produce following result:


Value of total : 30
Value of total : 40

Department of Engineering Sciences and Humanities, VIT, Pune


Default arguments
• A default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
• Following example gives idea on default arguments, it would print default
age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );

• This would produce following result:


Name: miki Age 50
Name: miki Age 35

Department of Engineering Sciences and Humanities, VIT, Pune


Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
• This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");

• This would produce following result:


My string

Department of Engineering Sciences and Humanities, VIT, Pune


Scope of Variables
• All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables

• Global vs. Local variables:


• Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
• This means that local variables can be accessed only inside the function in which
they are declared whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope.

Department of Engineering Sciences and Humanities, VIT, Pune


Scope of Variables
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total

• This would produce following result:


Inside the function local total : 30
Outside the function global total : 0

Department of Engineering Sciences and Humanities, VIT, Pune


Scope of Variables
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters“
global total
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total

• This would produce following result:


Inside the function local total : 30
Outside the function global total : 30

Department of Engineering Sciences and Humanities, VIT, Pune


SUMMARY
 Recursive Functions
 Function with more than one return value.
 Default value to parameter
 keyword parameter

Department of Engineering Sciences and Humanities, VIT, Pune


THANK YOU !!!

Department of Engineering Sciences and Humanities, VIT, Pune

You might also like