Notes Functions in Python 2022 23
Notes Functions in Python 2022 23
1. Types of Functions:
There are three types of functions in python:
1. Library Functions (Readymade) (Built in functions)
2. Readymade Functions defined in modules
3. User Defined Functions
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
1
2. Functions defined in modules: These functions defined in particular modules.
When you want to use these functions in program, you have to import the
corresponding module of that function.
Method 1:
(We are importing full module, and using function sqrt)
import math
a=16
print(math.sqrt(a))
Output : 4.4721
3. User Defined Functions: The functions those are defined by the user are called
user defined functions.
2
b. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in program.
These are also readymade functions. We donot have to write the code.
import math
S. No. Function Descriptio Exampl
n e
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
Example:
import random
n=random.randint(3,7)
3
def function-name ( parameters) :
#statement(s)
4
Where:
Example:
def display(name):
Function Parameters:
A functions has two types of parameters:
1. Formal Parameter: Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local variables which are
assigned values from the arguments when the function is called.
2. Actual Parameter: When a function is called, the values that are passed in the call
are called actual parameters. At the time of the call each actual parameter is
assigned to the corresponding formal parameter in the function definition.
6
2. Calling the function:
Once we have defined a function, we can call it from another function, program or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
ADD(p,r)
OUTPUT:
Sum = 30.0
• The execution of any program starts from the very first line and this execution goes line by line.
• One statement is executed at a time.
• Function doesn’t change the flow of any program.
• Statements of function do not start executing until function is called.
• When function is called then the control is jumped into the body of function.
• Then all the statements of the function gets executed from top to bottom one by one.
• And again the control returns to the place where it was called.
7
a. Function returning some value
def my_function(x):
return 5 * x
b. Function not returning any value The function that performs some operations
but does not return any value, called void function.
def message():
print("Hello")
message()
9
4. Scope and Lifetime of variables:
1. Local Scope
2. Global Scope
1. Local Scope: A variable declared inside the function's body or in the local scope is
known as a local variable.. It can not be accessed outside the function. In this scope,
The lifetime of variables inside a function is as long as the function executes. They
are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime
of a variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
10 Value outside
function: 20
10
Here, we can see that the value of x is 20 initially. Even though
the function my_func()changed the value of x to 10, it did not
affect the value outside the function.
We can read these values from inside the function but cannot
change (write) them. In order to modify the value of variables
outside the function, they must be declared as global variables
using the keyword global.
11
example, the previously defined function
f() may be called with keyword arguments. When Calling function :
greet(name =
Like with positional arguments, though, the "Bruce",msg = "How do
number of arguments and parameters must you do?")
still match.
z=area(7) # 7 will be
taken as r in the
function
z= area() # 2 will be
taken
def test(a,b=7):
print(a)
print(b)
print("**")
12
def test(a= 2,b): it will be error as default argument cannot follow positional argument in
header. Default arguments have to be rightmost
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it
willbe treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
a=float(input("Enter one"))
b=float(input("Enter second"))
t=(a,b)
y=try1(t) # a tuple is being passed to function
print(y) y gets 2 values in a tuple
Example 2 :
def func(tup):
print(tup)
print("*****")
print(tup[0])
print(tup[1])
print(tup[2])
Output:
13
return (c, a)
rad=float(input("Enter radius"))
cir,ar=f(rad)
print("circumference is ",cir)
print("Area is ",ar)
Output:
Enter radius3
circumference is 18.84
Area is 28.25
func(d1)
Output
dict_keys(['arg1', 'arg2', 'arg3'])
dict_values(['one', 'two', 'three'])
Example 2 :
Passing dictionary to a function. Deleting one key vaue pair . Returning the changed
dictionary to main program
def func(d):
del d["arg3"]
return(d)
v=func(d1)
print(v)
Output:
{'arg1': 'one', 'arg2': 'two'}
9. Unpacking
When specifying a list or tuple with * as an argument, it is unpacked, and each element is
passed to each argument.
Example
14
func(1,2,3) # integers 1,2,3 passed
l = ['one', 'two', 'three']
Output:
arg1 = 1
arg2 = 2
arg3 = 3
arg1 = one
arg2 = two
arg3 = three
arg1 = four
arg2 = five
arg3 = six
arg1 = one tuple
arg2 = two tuple
arg3 = three tuple
arg1 = four tuple
arg2 = five tuple
arg3 = six tuple
Output
arg1 = one
arg2 = two
15
arg3 = three
arg1 = one
arg2 = two
arg3 = three
While calling the function we pass values and called At the time of calling instead of passing the
as call by values. values we pass the address of the variables that
means the location of variables so called call by
reference.
When we pass arguments like whole numbers, When we pass mutable objects ,the passing is
strings or tuples to a function, the passing is call- call by reference i.e. when their values are
by-value because you can not change the value of changed inside the function, then it will also
the immutable objects being passed to the be reflected outside the function in the
function. passed argument
The changes are made to parameters in the called By using the address we have the access to the
function that have no effect on the actual actual parameters.
parameters of the function.
We cannot change the values of the actual variable We can change the values of the actual variable
through a function call. through a function call.
16
b=b+2
x=5
y=6
print("values of x, y before Accessing the function ", x, y)
func(x,y)
print("values of x, y after Accessing the function ", x, y)
Output:
values of x, y before Accessing the function
5 6
values of x, y after Accessing the function
5 6
In Lists, it is call def func(L1):
be reference for i in range(0,len(L1)):
L1[i]=0
If we send the same
numbers as above, # main code
but in the form of L=[]
List, it is Call be a=int(input("Enter value of a "))
Reference b = int(input("Enter value of b "))
L=[a,b]
print("values of L before Accessing the
function ", L)
func(L)
Output:
Enter value of a 5
Enter value of b 6
values of L before Accessing the function
[5, 6]
values of L after Accessing the function
[0, 0]
In Lists, it is Call def func(L1):
by Reference for i in range(0,len(L1)):
L1[i]=0
#main program
L=[1,2,3,4,5]
17
Output:
values of L before Accessing the function
[1, 2, 3, 4, 5]
values of L after Accessing the function
[0, 0, 0, 0, 0]
In Dictionary, it is def func(d):
call by reference. del d["arg3"]
We are passing a
dictionary. One key #main program
value pair is d1 = {'arg1': 'one', 'arg2': 'two', 'arg3':
deleted. 'three'}
In the main program
the change is print("Dictionary before Accessing the function
reflected in ", d1)
argument passed.
func(d1)
Output:
Dictionary before Accessing the function
Programs on Functions
ASSIGNMENT ON Functions
INPUT
1. WAP to find bigger number of two numbers. 2 numbers will be input in
main program. Use a function to return the bigger number.
18
y=int(input("enter another number"))
z=check(x,y) # x,y are actual parameters
print(z," is greater")
OUTPUT
enter a number45
enter another number67
67 is greater
19
return g
#program
a1=int(input("enter the value of base"))
b1=int(input("enter the value of exponent"))
j=power(a1,b1)
print(j)
OUTPUT
enter the value of base6
enter the value of exponent3
216
INPUT
4. WAP to count positive numbers in the list. In the main program, input the
list. Use a function to count positive nos.
def poscount(list1):
pcount=0
return pcount
#program
lst=[]
n=int(input("enter the number of elements in the list"))
for i in range (0,n):
element=int(input("Pl enter element"))
lst.append(element)
print(lst,"your list")
g=poscount(lst) # poscount named function called here
print("No of positive are ",g)
20
OUTPUT
enter the number of elements in the list10
2
-4
56
-57
9
-3
3
3
4
-5
[2, -4, 56, -57, 9, -3, 3, 3, 4, -5] your list
no.of positive numbers in list 6
#program
n=int(input("enter number of terms"))
g=fibo(n)
OUTPUT
21
enter number of terms6
1
2
3
5
8
13
INPUT
6. WAP to input 2 numbers. Use a function to swap(exchange) their values.
def swap():
global a
global b
temp=a
a=b
b=temp
#program
a=int(input("enter first number"))
b=int(input("enter second number"))
swap() # swap function being called
print(a,"first number")
print(b,"second number")
OUTPUT
enter first number56
enter second number78
78 first number
56 second number
INPUT
22
7. WAP to let the user enter temperature and choice whether he/she wants
to convert Celcius to Fahrenheit or Vice Versa. Use 2 functions to do as
required.
def tswap1(c):
f=((9*c)/5)+32
print(f,"is the temp in fahrenheit")
def tswap2(f):
c=(5/9)*(f-32)
print(c,"is the temp in celcius")
#program
print("enter 'c' to convert the temp from celcius to fahrenheit")
print("enter 'f' to convert the temp from fahrenheit to celcius")
n=input()
if n=="c":
celcius=int(input("enter temp in celcius"))
i=tswap1(celcius)
elif n=="f":
fahrenheit=int(input("enter temp in fahrenheit"))
i=tswap2(fahrenheit)
OUTPUT
enter 'c' to convert the temp from celcius to fahrenheit
enter 'f' to convert the temp from fahrenheit to celcius
c
enter temp in celcius40
104.0 is the temp in fahrenheit
def unique_list(l):
x = []
for a in l:
23
if a not in x:
x.append(a)
return x
print(unique_list([1,1,3,3,3,3,4,5]))
Output:
[1, 3, 4, 5]
9. WAP to input a numbers. Use a function to check whether its a Prime
number or not.
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(13))
10. WAP to pass a list with fruit names to a function. . Use a function to print
the passed elements of list in separate lines.
def my_function(food):
for x in food:
print(x)
my_function(fruits)
WAP to input a list in the main
def change(list1):
listnew=[]
for num in list1:
24
if num >=0:
num=0
listnew.append(num)
else:
num=-1
listnew.append(num)
return(listnew)
#program
lst=[]
n=int(input("enter the number of elements in the list"))
for i in range (0,n):
element=int(input("Pl enter element"))
lst.append(element)
print(lst,"your list")
g=change(lst) # poscount named function called here
print(g)
11.
def isPalindrome(str):
# main program
Output:
Enter a String to check malyaylam
Yes its a Palindrome
Enter a String to check geeta
25
No- its not a Palindrome
Questions
26