Module 5
Module 5
FUNCTIONS
1. Built-in function
2. User-defined function
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
06-07-2024 Dr. V.Srilakshmi 5
Function Example
# function
def message():
print("Welcome to VIT-AP")
message()
# 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
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)
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.
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
def f(x):
return 6*x**2 + 3*x + 2
y = f(2)
print y
Example:
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
if result==True:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
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)
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]))
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]
def function1():
def function2():
print("Hello Function-1")
function2()
print("Hello Function-2")
function1()
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)
def toh(n,start,end,aux):
if(n==1):
print("Move disk 1 from",start,"to",end) Enter the number of disks: 3
• 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)
• datetime
• random
• math
• statistics
import math
x = platform.system()
print(x)
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
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
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
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]
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"
factorial_result = fact(random_number)
print("Factorial of random_number:”,factorial_result)