0% found this document useful (0 votes)
216 views

Notes Functions in Python 2022 23

The document discusses functions in Python, including defining and calling user-defined functions, built-in functions, and functions in modules. It covers function parameters and arguments, returning values, and the flow of execution when a function is called. Specifically, it defines functions as blocks of code that perform tasks when called, and discusses defining functions with and without arguments and return values. It also provides examples of built-in math functions, random functions, and user-defined functions.

Uploaded by

ishan arora
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)
216 views

Notes Functions in Python 2022 23

The document discusses functions in Python, including defining and calling user-defined functions, built-in functions, and functions in modules. It covers function parameters and arguments, returning values, and the flow of execution when a function is called. Specifically, it defines functions as blocks of code that perform tasks when called, and discusses defining functions with and without arguments and return values. It also provides examples of built-in math functions, random functions, and user-defined functions.

Uploaded by

ishan arora
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
You are on page 1/ 26

FUNCTIONS IN PYTHON

CBSE 2022-23 Functions: scope, parameter passing,


mutable/immutable properties of data objects, passing
strings, lists, tuples, dictionaries to functions, default
parameters, positional parameters, return values,
functions using libraries: mathematical and string
functions.

Definition: Functions are the subprograms that perform specific task.


 A function is a block of code that only runs when it is called.
 Python functions return a value using a return statement, if return ststement is
specified. If not specified, function doesn’t return a value.
 A function can be called anywhere after the function has been declared.

 A function can be called any number of times.


 By itself, a function does nothing. It gets executed only when called.

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

User defined functions

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.

• Module is a file that has variables and functions.


• Every function in a module is for a definite task
• Once a module is made, we can use it in different
programs
• Suppose we are writing one function or more functions that has to be used in a
different program, then we write it in a Module. Then we import that module in a
program and can use the functions inside the module.

• There are 2 methods

Importing Python Modules

Method 1:
(We are importing full module, and using function sqrt)

import math
a=16
print(math.sqrt(a))

Output : 4.4721

Method 2: (We are not importing full module, only the


function sqrt)
from math import sqrt
a=16
print(sqrt(a))

3. User Defined Functions: The functions those are defined by the user are called
user defined functions.

a. Library Functions in Python:


These functions are already built in the library of python.
For example: type( ), len( ), input( ) etc.

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

b. Function in random module:


random module has a function randint( ).
i. randint( ) function generates the random integer values including
start and end values.
ii. Syntax: randint(start, end)
iii. It has two parameters. Both parameters must have integer values.

Example:
import random
n=random.randint(3,7)

*The value of n will be 3 to 7.

c. USER DEFINED FUNCTIONS:

The syntax to define a function is:

3
def function-name ( parameters) :
#statement(s)

4
Where:

 First statement of function like def sum(a,b): is a header.


 Keyword def marks the start of function header.
 A function name uniquely identifies the function . Function naming follows
the same rules a s of naming identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are
optional.
 A colon (:) to mark the end of function header.
 One or more valid python statements that make up the function body.
Statements in the function are indented and must have same indentation
level.
 An optional return statement is used to return a value from the function.

Example:

def display(name):

print("Hello " + name + " How are you?")

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.

Difference between Parameters and Arguments


A parameter is the variable listed inside the parentheses in the function definition. An
argument is the value that are sent to the function when it is called.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters
5
z=x+y
print("Sum = ", z)

a=float(input("Enter first number: " ))


b=float(input("Enter second number: ))
ADD(a,b) #Calling the function by passing actual parameters/arguments
In the above example, x and y are formal parameters. X, y are local variables in the
function .
a and b are actual parameters.

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

Flow of Execution at the Time of Function Call

• 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.

3. The return statement:


The return statement is used to exit a function and go back to the place from
where it was called.
There are two types of functions according to return statement:
a. Function returning some value
b. Function not returning any value

7
a. Function returning some value

Example-1: Function returning one 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()

Types of calling of Functions Examples

Function without arguments and def Add1():


without return statement a = 20
sum = a + b
print(Sum)

Add1() Calling the function


Function with arguments and
without return statement def Add2(a,b): # a,b are formal arguments
Sum = a + b
print("Result:", Sum)

Add2(20,30) #Calling the function here.


#Sending Parameters. 50 printed

Add2(10,20) #30 will be printed

Function with arguments and with def Add2(a,b):


return statement Sum = a + b
return(Sum)

z=Add2(20,30) Calling the function


8
print("Result:", z)

Function without arguments and


with return statement def Add2():
a= input(“Enter
b= input(“Enter a value”)
Sum = a + b
return(Sum)

z=Add2() Calling the function


print("Result:", z)

9
4. Scope and Lifetime of variables:

Scope of a variable is the portion of a program where the variable is recognized.


Parameters and variables defined inside a function is not visible from outside. Hence,
they have a local scope.

There are two types of scope for 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:

Value inside function:

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.

This is because the variable x inside the function is different


(local to the function) from the one outside. Although they have
same names, they are two different variables with different
scope.

On the other hand, variables outside of the function are visible


from inside. They have a global
scope.

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.

5. Types of Arguments in Functions


Example
The most commonway to pass arguments to def Add2(a,b):
Positional a Python function is with positional Sum = a + b
Arguments arguments (also called required return(Sum)
arguments).

In the function definition, you specify a


comma-separated list of parameters inside x=7
the parentheses y=2
z=Add(x,y)
When the function is called, you specify a #Calling the
corresponding list of arguments in the function
respective order
x is for a
With positional arguments, the arguments y is for b
in the call and the parameters in the
definition must agree not only in order
but in number as well.

When you’re calling a function, you can Suppose function is :


Keyword specify arguments in the form
Argument <keyword>=<value>. def greet(msg,name):

Each <keyword> must match a parameter in


the Python function definition. For

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.

greet(msg = "How do you


do?",name = "Bruce")

If we combine keyword and


positional arguments then
keyword arguments must
follow positional arguments)

Default If a value for argument is not supplied at def area(r= 2):


argument the time of function call, and if default a= 3.14*r*r
argument is given, then default will be return(a)
taken .

z=area(7) # 7 will be
taken as r in the
function

z= area() # 2 will be
taken

def area( l, b=5): valid


def area(b=5,l) : Invalid as default arguments should be rightmost
def sum(a,b=2,c=5) valid
def sum(a=2,b,c=5) invalid as default arg should be rightmost

def test(a,b=7):
print(a)
print(b)
print("**")

test(5,6) # will print 5 and 6


test(5) # will print 5 and 7
test(a=2,b=3)# will print 2 and 3
test(5,b=4) # will print 5,4
test(a=2,b) # will give error
as positional argument cannot follow keyword argument

Also in the Function Header If I write :

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:

6. Function getting Tuple as argument


Example 1:
def try1(x): #try1 function receives a tuple and returns it
return(x)

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])

t = ('one tuple', 'two tuple', 'three tuple')


func(t)

Output:

('one tuple', 'two tuple', 'three tuple')


*****
one tuple
two tuple
three tuple

7. Functions Returning Tuple


def f(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14 * r
a = 3.14 * r * r

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

8. Passing Dictionary to function


def func(d):
print(d.keys())
print(d.values())

d1 = {'arg1': 'one', 'arg2': 'two', 'arg3': 'three'}

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)

d1 = {'arg1': 'one', 'arg2': 'two', 'arg3': 'three'}

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.

Dictionary is unpacked using **

Example

def func(arg1, arg2, arg3):


print('arg1 =', arg1)
print('arg2 =', arg2)
print('arg3 =', arg3)

14
func(1,2,3) # integers 1,2,3 passed
l = ['one', 'two', 'three']

func(*l) #l is a list being passed as individual elements

func(*['four', 'five', 'six'])

t = ('one tuple', 'two tuple', 'three tuple')

func(*t) #t is a tuple being pased as ind elements

func(*('four tuple', 'five tuple', 'six tuple'))

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

10. Unpacking Dictionary and Passing


def func(arg1, arg2, arg3):
print('arg1 =', arg1)
print('arg2 =', arg2)
print('arg3 =', arg3)

d = {'arg1': 'one', 'arg2': 'two', 'arg3': 'three'}

func(**d) #unpacking dictionary and passing

func(**{'arg1': 'one', 'arg2': 'two', 'arg3': 'three'})#unpacking


#dictionary and passing

Output
arg1 = one
arg2 = two

15
arg3 = three
arg1 = one
arg2 = two
arg3 = three

11. Call by Value & Call by Reference

Call by value Call by reference


Call by value:-The parameter values are copied to Call by reference:-
function parameter and then two types of The actual, as well as the formal parameters
parameters are stored in the memory locations. refer to the same location and if changes are
When changes are made to the parameters in the made inside the functions, the change(s) are
function, the changes are not reflected in the reflected in the actual parameter of the
parameter of the calling code. calling code.

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.

Example of Call by value and Call by reference

In numbers, it is def func(a,b):


Call by Value a=a+2

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)

print("values of L after Accessing the


function ", 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]

print("values of L before Accessing the function ", L)


func(L)
print("values of L after Accessing the function ", L)

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)

print("Dictionary after Accessing the function


", d1)

Output:
Dictionary before Accessing the function

{'arg1': 'one', 'arg2': 'two', 'arg3': 'three'}

Dictionary after Accessing the function


{'arg1': 'one', 'arg2': 'two'}

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.

def check(a,b): # a,b are formal parameters


if a>b:
return a
elif b>a:
return b
else:
print(a,"=",b)
#main
x=int(input("enter a 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

2. WAP to find Factorial of a number that is entered in main program. Use a


function
def fact(n): # n is formal argument
if n==0
return 1
elif n==1:
return 1
else:
product = 1
for i in range (1,n+1):
product = product * i
return product
#program
s =int(input("enter a number "))
h = fact(s) # s is the actual argument
print(h,"is the factorial of",s)
OUTPUT
enter a number 3
6 is the factorial of 3
INPUT
3. WAP to input 2 integers- base and exponent . Use a function to return
base raise to exponent. Assume there is no readymade function.
def power(b,e):
g=b**e

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

for num in list1:


if num >=0:
pcount+=1

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

5. WAP to input number of terms in fibonacci series in the main program.


Use a function that accepts the number of terms as argument and the function
is used to display the series
def fibo(n):
a=1
b=2
print(a)
print(b)
for i in range (2,n):
c=a+b
a=b
b=c
print(c)

#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

8. WAP to input a list of integers. Display the numbers without duplicates

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)

fruits = ["apple", "banana", "cherry"]

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):

# Run loop from 0 to len/2


for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True

# main program

s = input("Enter a String to check ")


ans = isPalindrome(s)
if (ans==True):
print("Yes its a Palindrome")
else:
print("No- its not a Palindrome")

Output:
Enter a String to check malyaylam
Yes its a Palindrome
Enter a String to check geeta

25
No- its not a Palindrome

Questions

1. What is a function in Python? Distinguish between Userdefined and Library


functions.

2. Differentiate between actual parameters and formal parameters. Give a suitable


example also.
3. Differentiate between value and reference parameters. Give a suitable example
also.
4. What is meant by the scope of a variable?
5. Differentiate between local and global variables. Give a suitable example also.
6. What is the use of keyword global?
7. Can a function have a local variable with the same name as that of a global
variable in the script? If yes, then is it possible to access global variable with the same
name in that function? If yes, how?
8. What is the use of return statement in a function? In which three cases does a
function return None?
9. What is the difference between mutable and immutable data objects being passed
as
arguments to a function?
10. What is a function header? Give an example.

26

You might also like