Module-5
FUNCTIONS
Pre-defined functions, User defined functions, formal and actual
parameters, return statement, Using Branching, Looping and Data
structures in Functions, Recursion, Internal workflow of Recursion,
Modules.
06-07-2024 Dr. V.Srilakshmi 1
Functions
• In Python, function is a group of related statements that perform a
specific task.
• A function is a piece of code that groups a set of statements so they can
be run/called more than once in a program
• A function is a block of code which only runs when it is called.
• Python has a DRY (Don’t Repeat Yourself) principle.
• The benefit of using a function is reusability and modularity.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
06-07-2024 Dr. V.Srilakshmi 2
Types of Functions
Python support two types of functions
1. Built-in function
2. User-defined function
06-07-2024 Dr. V.Srilakshmi 3
Built-in function
❖The functions which are come along with Python itself are
called a built-in function or predefined function
range(), append(), type(), input(), len()
for i in range(1, 10):
print(i, end=' ')
# Output 1 2 3 4 5 6 7 8 9
06-07-2024 Dr. V.Srilakshmi 4
User-defined function
❖Functions which are created by programmer explicitly according to the
requirement are called a user-defined function. parameter: Parameter is the value
passed to the function. We can pass
def function_name(parameter1, parameter2): any number of parameters. Function
# function body body uses the parameter’s value to
# write some action perform an action
return value
function_body: The function body
is a block of code that performs some
def keyword is used to define a function. task. This block of code is nothing but
the action you wanted to accomplish.
function_name: Function name is the
name of the function. We can give any return value: Return value is the
name to function. output of the function.
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
06-07-2024 Dr. V.Srilakshmi 5
Function Example
06-07-2024 Dr. V.Srilakshmi 6
How to call a function in python?
• To call a function we simply type the function name with appropriate
parameters.
Ex1:
def greet():
print("Hello, Good morning!")
greet() #function call
Ex2:
def greet2(name):
print("Hello, " , name , ". Good morning!")
greet2(“ram”)
06-07-2024 Dr. V.Srilakshmi 7
Creating a function without any parameters
# function
def message():
print("Welcome to VIT-AP")
message()
06-07-2024 Dr. V.Srilakshmi 8
Creating a function with parameters
# function
def course_func(name, course_name):
print("Hello", name, "Welcome to VIT-AP")
print("Your course name is", course_name)
# call function
course_func(“John”, “Python”)
Output:
Hello John Welcome to VIT-AP
Your course name is Python
06-07-2024 Dr. V.Srilakshmi 9
The return statement
• We can return the result or output from the function using a 'return'
statement in the body of the function
• If a function does not return any result, we need not write the return
statement in the body of the function
Syntax of return : return expression_list
06-07-2024 Dr. V.Srilakshmi 10
Creating a function with parameters and return value
def calculator(a, b):
add = a + b
return add # return the addition
res = calculator(20, 5) # take return value in
variable
print("Addition :", res) Output:
Addition : 25
06-07-2024 Dr. V.Srilakshmi 11
Returning multiple values form a function
• A function returns a single value in the programming languages like C or Java.
• But in python, a function can return multiple values.
• When a function calculates multiple results and wants to return the results, we
can use the return statement as:
return a, b, c
• Here, three values which are in 'a', 'b', and 'c' are returned.
• These values are returned by the function as a tuple.
To grab these values, we can use three variables at the time of calling the function
as:
x, y, z = function()
• Here, the variables ‘x’, 'y' and 'z' are receiving the three values returned by the
function.
06-07-2024 Dr. V.Srilakshmi 12
Returning multiple values form a function
def calculator(a, b):
add = a + b
sub = a - b
mul = a * b
Addition : 25
return add,sub,mul Subtraction: 15
Multiplication : 100
# call function
# take return value in variable
res1,res2,res3 = calculator(20, 5)
print("Addition :", res1)
print("Subtraction:", res2)
print("Multiplication :", res3)
06-07-2024 Dr. V.Srilakshmi 13
Scope of variables
• Scope of a variable is the portion of a program where the variable is visible.
• In Python, a variable declared outside of the function is known as global variable.
• This means, global variable can be accessed inside or outside of the function.
• A variable declared inside the function's body is known as local variable.
x = 20 #global variable/scope
def my_func():
x = 10 #Local variable/Scope
print("Value of X inside function:",x)
my_func()
print("Value of X outside function:",x)
06-07-2024 Dr. V.Srilakshmi 14
formal and actual parameters
• Parameter refers to the information passed to the function.
• Parameters are also known as arguments.
• Formal Parameters are the parameters which are specified during the definition
of the function.
• Actual Parameters are the parameters which are specified during the function
call.
def sum(a, b):
return a + b
sum(5,6)
In the above code, ‘a’ & ‘b’ are formal parameters and ‘5’ &’6’ actual parameters
06-07-2024 Dr. V.Srilakshmi 15
Actual Parameters or Arguments
Actual Parameters are four types :
1. Positional Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable-length Arguments
06-07-2024 Dr. V.Srilakshmi 16
Positional Arguments
• These are the most common type of parameters.
• The values are passed based on the order of parameters in the function
definition.
Example:
def result(name, marks): Output:
print("Name of student : ", name) Name of student : Veda
cgpa = marks/10
CGPA is : 9.5
Name of student : 9.0
print("CGPA is : ", cgpa)
CGPA is : Dolly
result("Veda",95)
result(90, "Dolly")
06-07-2024 Dr. V.Srilakshmi 17
Write a Python function to calculate 6*x**2 + 3*x + 2, that
takes x as input.
def f(x):
return 6*x**2 + 3*x + 2
y = f(2)
print y
06-07-2024 Dr. V.Srilakshmi 18
Keyword Arguments
• In this type, arguments are identified by their parameter names.
• you can specify the arguments by the names of their corresponding parameters
with values even in a different order from their definition in the function
Example:
def result(name, marks):
print("Name of student : ", name) Name of student : Veda
cgpa = marks/10 CGPA is : 9.5
print("CGPA is : ", cgpa) Name of student : Dolly
CGPA is : 9.0
result(name="Veda",marks=95)
result(marks=90,name="Dolly")
06-07-2024 Dr. V.Srilakshmi 19
Default Arguments
• You can set default values for parameters in the function definition.
• If a value is not provided for a parameter during the function call, the default value is
used.
Example:
# default Arguments
def result(name, marks=80):
print("Name of student : ", name)
cgpa = marks/10
print("CGPA is : ", cgpa) Name of student : Veda Sri
CGPA is : 8.0
result("Veda Sri") Name of student : Dolly
result("Dolly",70) CGPA is : 7.0
06-07-2024 Dr. V.Srilakshmi 20
Variable-length arguments
• These are used when you want to pass a variable number of arguments to a function.
• When * used inside the function with a parameter then asterisk groups a variable
number of positional arguments into a tuple of parameter values.
def result(name, *marks):
print("Name of student : ", name)
total= sum(marks) Name of student : Hari
nc=len(marks)
cgpa=total/nc Total Marks : 270
Total No of courses : 3
print("Total Marks : ", total) CGPA is : 90.0
print("Total No of courses : ", nc)
print("CGPA is : ", cgpa)
result("Hari",80,90,100)
06-07-2024 Dr. V.Srilakshmi 21
Income tax calculator
def calculate_income_tax(income):
if income <= 500000:
tax = 0
elif income > 500000 and income <= 1000000:
tax = 0.1 * income
elif income > 1000000 and income <= 1500000:
tax = 0.2 * income
else:
tax = 0.3 * income Enter your annual income: 1200000
Your income tax is: 240000.00
return tax
income = float(input("Enter your annual income:"))
tax = calculate_income_tax(income)
print(f"Your
06-07-2024
income tax is:{tax:.2f}")
Dr. V.Srilakshmi 22
Check weather given number is prime or not
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
num = int(input("Enter a number to check if it's prime: "))
result=is_prime(num)
if result==True:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
06-07-2024 Dr. V.Srilakshmi 23
Check weather given number is palindrome or not
def palindromeCheck(num):
temp = num
rev = 0
while(num != 0):
r = num%10
rev = rev*10+r
num = num//10
if(rev == temp):
print(temp, "is a palindrome number")
else:
print(temp, "is not a palindrome number")
palindromeCheck(131)
palindromeCheck(34)
131 is a palindrome number
06-07-2024 Dr. V.Srilakshmi 24
34 is not a palindrome number
Sum of list numbers
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
result=sum([8, 2, 3, 0, 7])
print(result)
06-07-2024 Dr. V.Srilakshmi 26
#Even elements from list
def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
06-07-2024 Dr. V.Srilakshmi
[2, 4, 6, 8] 27
Write a Python function that takes a list and returns a new list with
distinct elements from the first list.
def unique_list(numbers):
x=set(numbers) #unique numbers in set
y=list(x) #convert set to list
return y
result=unique_list([2,3,4,3,5,3])
print(result)
[2, 3, 4, 5]
06-07-2024 Dr. V.Srilakshmi 28
Python nested functions
def function1():
def function2():
print("Hello Function-1")
function2()
print("Hello Function-2")
function1()
06-07-2024 Dr. V.Srilakshmi 29
Recursion
• A function calls itself one or more times in its body is called recursion.
• A function which calls itself is called a recursive function.
06-07-2024 Dr. V.Srilakshmi 30
Example 1: Finding the factorial of a number
• In mathematics, the equation for finding the factorial of a number is as
follows: n! = n * (n-1)!
def fact(n):
if(n==1):
return 1 Enter a number: 4
else:
return n*fact(n-1) Factorial is: 24
num = int(input("Enter a number: "))
result=fact(num)
print("Factorial is: ",result)
06-07-2024 Dr. V.Srilakshmi 31
Example 2: Fibonacci Series
0, 1, 1, 2, 3, 5, 8, 13,…
• In this series, the next number is found by adding the two numbers before that.
#Fibonacci nth term #Fibonacci series
def fib(n):
if n<=1: def fib(n):
return n if n<=1:
else: return n
return fib(n-1) + fib(n-2) else:
return fib(n-1) + fib(n-2)
num = int(input("Enter the nth term: "))
result=fib(num) num = int(input("Enter the limit: "))
print(result) for i in range(num):
print(fib(i),end=" ")
Enter the nth term: 6 Enter the limit: 5
8 01123
06-07-2024 Dr. V.Srilakshmi 32
Example 3: Finding the power of a number
• The mathematical equation for finding the power of a number is as follows:
p(base, exp) = base * p(base, exp-1)
For example, 23 = p(2, 3) = 2 * p(2,2)
def power(base,exp):
if exp == 0:
return 1 Enter the base value: 2
if exp==1: Enter the exponent value: 3
return base
else: The result is: 8
return base*power(base,exp-1)
b = int(input("Enter the base value: "))
e = int(input("Enter the exponent value: "))
print("The result is:", power(b,e))
06-07-2024 Dr. V.Srilakshmi 33
Example 5: Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the
puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
06-07-2024 Dr. V.Srilakshmi 35
Example 5: Tower of Hanoi
def toh(n,start,end,aux):
if(n==1):
print("Move disk 1 from",start,"to",end) Enter the number of disks: 3
return Move disk 1 from A to B
Move disk 2 from A to C
toh(n-1,start,aux,end) Move disk 1 from B to C
Move disk 3 from A to B
print("Move disk",n,"from",start,"to",end) Move disk 1 from C to A
Move disk 2 from C to B
toh(n-1,aux,end,start) Move disk 1 from A to B
n = int(input("Enter the number of disks: "))
toh(n,'A','B','C')
06-07-2024 Dr. V.Srilakshmi 36
Anonymous Functions
• Anonymous functions, also known as lambda functions, are functions that are
defined without a name.
• Instead of using the def keyword to define a function with a name, you use the
lambda keyword to create a small, unnamed function.
• Anonymous functions are often used for short, simple operations.
Syntax: lambda arguments: expression
• Lambda functions can have any number of arguments but only one expression.
• The expression is evaluated and returned
Example:
add = lambda x, y: x + y numbers = [1, 2, 3, 4, 5]
result = add(3, 5) squared = list(map(lambda x: x**2, numbers))
print(result) # Output: 8 print(squared)
[1, 4, 9, 16, 25]
06-07-2024 Dr. V.Srilakshmi 37
Modules
• Python Module is a file that contains built-in functions, classes, and
variables.
• Modules refer to a file containing Python statements and definitions.
• A module can define functions, classes and variables.
• Modules provide reusability of code.
• We can define our most used functions in a module and import it,
instead of copying their definitions into different programs.
06-07-2024 Dr. V.Srilakshmi 38
Built-in modules
• datetime
• random
• math
• statistics
06-07-2024 Dr. V.Srilakshmi 39
import math
#Return factorial of a number import math
print(math.factorial(3))
print(math.factorial(5)) print(math.pow(2, 3))
import math
import math T= (1, 2, 3)
L = (3, 4, 5)
print (math.sqrt(9)) #Return the product of the elements
print (math.sqrt(25)) print(math.prod(T))
print(math.prod(L))
06-07-2024 Dr. V.Srilakshmi 40
import datetime
x = datetime.datetime.now()
print(x)
#returns a number between 3 and 9 (both included)
import random
print(random.randint(3, 9))
#Print mean, variance, stdev
import statistics
# Calculate average values
print(statistics.mean([1, 3, 5, 6])) 3.75
print(statistics.variance([1, 3, 5, 6])) 4.916666666666667
print(statistics.stdev([1, 3, 5, 6])) 2.217355782608345
06-07-2024 Dr. V.Srilakshmi 41
import platform
x = platform.system()
print(x)
dir() function list all the function names (or variable
names) in a module.
import math
x = dir(math)
print(x)
06-07-2024 Dr. V.Srilakshmi 42
Create a Module
• To create a module just save the code you want in a file with the
file extension .py
create a module and save it as arithmetic.py.
def add(a,b) :
c=a+b
return c
def sub(a,b):
c=a-b
return c
06-07-2024 Dr. V.Srilakshmi 43
importing modules in Python
• We can import a module using import statement and access the definitions
inside it using the dot operator.
syntax −
import module1[, module2[,... moduleN]
Ex:
import arithmetic
d=arithmetic.add(5,6)
s=arithmetic.sub(5,6)
print("addition",d)
print("sub",s)
06-07-2024 Dr. V.Srilakshmi 44
import with renaming
• We can import a module by renaming using as keyword.
syntax −
import module as newname
Ex: import arithmetic as ar
a=int(input())
b=int(input())
d=ar.add(a,b)
if(d%2==0):
print("Result of addition is a even number")
else:
print("Result of addition is a odd number")
06-07-2024 Dr. V.Srilakshmi 45
Import From Module
• You can choose to import only parts from a module, by using
the from keyword.
arithmetic.py
addonly.py
def add(a,b) :
c=a+b
from arithmetic import add
return c
d=add(7,6)
def sub(a,b):
print("addition",d)
c=a-b
return c
06-07-2024 Dr. V.Srilakshmi 46
Import From Module
• You can choose to import all parts from a module, by specifying * .
arithmetic.py
sample.py
def add(a,b) :
c=a+b from arithmetic import *
return c d=add(7,6)
def sub(a,b): print("addition",d)
c=a-b
return c
06-07-2024 Dr. V.Srilakshmi 47
Create a module named prime.py with one function prime (n) with number as parameter and return that
number is prime or not. Create a separate Python program (e.g., calculate_prime.py) to use the prime.py
module to print the prime numbers in the given list.
calculate_prime.py:
prime.py
import prime as p
numbers=[2,4,7,10,13]
def is_prime(num):
final=[]
if num < 2:
for i in numbers:
return False
result=p.is_prime(i)
for i in range(2, num):
if result==True:
if num % i == 0:
final.append(i)
return False
return True
print (final) O/P: [2,7,13]
06-07-2024 Dr. V.Srilakshmi 48
Create a module named evenodd.py with one function evenodd (n) with number as parameter and return that
number is even or odd. Create a separate Python program (e.g., guess.py) to use the evenodd.py module to guess
the randomly generated number between 1 to 100 is even or odd.
guess.py:
evenodd.py
import random
import evenodd as eo
def evenodd(n):
if n % 2 == 0:
random_number = random.randint(1, 100)
return "Even"
else:
result = eo.evenodd(random_number)
return "Odd"
print(f"Random Number: {random_number}")
print(f"The number is {result}.")
O/P: Random Number: 75
The number is Odd.
06-07-2024 Dr. V.Srilakshmi 49
Python program that generates a random number between 1 and 20 and then prints its
factorial.
import random
import math
O/P: Random Number: 4
def fact(n):
Factorial of 4: 24.
if n== 0 or n == 1:
return 1
else:
return n * fact(n - 1)
random_number = random.randint(1, 20)
print("Random Number:", random_number)
factorial_result = fact(random_number)
print("Factorial of random_number:”,factorial_result)
06-07-2024 Dr. V.Srilakshmi 50