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

Function

Uploaded by

deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Function

Uploaded by

deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Function

A function is a subprogram that acts on data and often returns a value


ADVANTAGES
Program Program testing Code sharing Code re-usability Increases
development becomes easy becomes possible increases program
made easy and readability
fast

Types of Functions
Built –in functions Functions defined in the modules User defined functions
(Pre-defined functions) (function using (defined by the programmer)
Libraries/modules)
int(),type(),float(),str(), sin(),floor(),ceil(),dump(),load() PARTS OF USER DEFINED
print(),input(),ord(), hex ,random(),writer() etc FUNCTIONS
(), oct() , len() etc • Function definition(def keyword)
• Arguments( function calling)
• Parameters( function definition)
• Function Calling

Note: parameters/ arguments are the variables/values what are provided in the function definition/calling.
Categories of user defined functions
void functions Non void functions
those functions which are not returning values to those functions which are returning values to the
the calling function calling function
return value can be literal, variable , expression

The basic structure of user defined function.


def funtionname(parameters name):
statement of the function
function_calling(arguments)

Q What are Arguments and Parameters?

Arguments Parameters
passed values in function call received values in function definition.
Passed values can be in the form of variable, It should be of variable types.
literal or expression
def fun(a,b): def fun(a,b): #parameters
c=a+b c=a+b
print(c) print(c)

x=2 here a and b are the parameters


y=4
fun(x,y) #variables
fun(5,6) #literals
fun(x+3,y+6) #expressions
here x,y , 5,6, x+3, y+3 are arguments

Q What are actual and formal arguments /parameters?

Formal parameter Actual Parameter


A formal parameter, i.e. a parameter, is in the An actual parameter, i.e. an argument, is in a
function definition. function call.

def sum(x,y): #x, y are formal arguments


z=x+y
return z #return the result

x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)

Q What is the use of return statement?


Ans It is used to return either a single value or multiple values from a function.
Q Can Python return Multiple values and in what forms?

Ans Python returns Multiple values in the form of tuples :

1. e.g.
Received values as tuple def fun(a,b):
return a+b,a-b
x=2
y=4
z=fun(x,y)
print(z)
2. e.g.
Unpack received values as tuple def fun(a,b):
return a+b,a-b
x=2
y=4
d,z=fun(x,y)
print(d,z)

Q Explain different types of arguments in detail


Ans
1. 2. Default Arguments- if right parameter 3.
Positional have default value then left parameters Keyword Arguments
parameters can also have default value. this argument (Named Arguments)-
(Required can be skipped at the time of function
Arguments) - these calling
arguments must be We can write arguments in any
provided for all order but we must give values
parameters according to their name
e.g. e.g. e.g.
def fun(a,b): def fun(a,b,c=3): def fun(a,b,c):
c=a+b d=a+b+c print(a,b,c)
print(c) print(d)
x=10 x=10 fun(b=3,c=4,a=2)
y=3 y=3
fun(x,y) fun(x,y) #here c parameter value is 3
z=5
fun(x,y,z) #here it will be take parameter c
value as 5

Q What do you mean by scope of variables?


Ans Scope means –to which extent a code or data would be known or accessed. 2 types of scope are: Global scope and
Local scope.

Global variable Vs Local Variable


Global variable Local Variable
Global variables are defined outside of all the A local variable is declared within the body of
functions, generally on top of the program. a function or a block
The global variables will hold their value Local variable only use within the function or
throughout the life-time of your program. block where it is declare.

a=10 //global variable


def fun():
b=20
print(b) //local variable
print(a)
Naming Resolution- LEGB-(LOCAL, ENCLOSED, GLOBAL and BUILT-IN)
1. Variable in global scope not in local 2. Variable neither in in local scope nor
scope in global scope
e.g e.g.
def fun1(x,y): def fun():
s=x+y print(“hello”,n)
print(num1) fun()
return s #
num1=100 Output:
num2=200 Name error: name ‘n’ is not defined
sm=fun1(num1,num2)
print(sm)
3. Variable name in local scope as well as in 4. Using global variable inside local scope
global scope (this case is discouraged in programming)
e.g. e.g.
def fun(): def fun():
a=10 # output global a
print(a) 5 a=10 # output
a=5 print(a)
10 5
print(a) a=5
fun() 5 print(a) 10
print(a) fun() 10
print(a)

Function Questions
Write a function that receives two numbers Write a function that takes a positive integer and returns
and generates a random number from that the ones position digit
range and prints it. of the integer. E.g. if the integer is 432, then the function
import random should return 2.
def generate(x,y):
n=random.randint(x,y)
print(n) def convert(x):
print(x%10)

Write a program having a function that Write a small python function that receive two numbers
takes a number as argument and and return their sum, product, difference
calculates cube for it. The function does not and multiplication.
return a value. If there is no return
value passed to the function in function call,
def calc(x,y):
retun x+y,x*y,x-y
the function should calculate cube
of 2.
def calc(x=2):
print(x**3)
calc(5)
calc()

Write the definition of a function Alter(A, Write the definition of a function Alter(A, N) in python,
N) in python, which should change all the which should change all the odd numbers in the list to 1
multiples of 5 in the list to 5 and rest of the and even numbers as 0.
elements as 0. #sol
#sol
def Alter(A,N): def Alter(A,N):
for i in range(len(A)): for i in range(len(A)):
if A[i]%5==0: if A[i]%2==1:
A[i]=5 A[i]=1
else: else:
A[i]=0 A[i]=0

Write code for a function oddEven (s, N) in Write a code in python for a function Convert ( T,
python, to add 5 in all the odd values and 10 in N) , which repositions all the elements of array by shifting
all the even values of the list 5. each of them to next position and shifting last element to
#sol first position.
e.g. if the content of array is
0 1 2
10 14 11
def Alter(A,N):
for i in range(len(A)):
if A[i]%5==0:
A[i]+=5
else:
A[i]+=10
The changed array content will be:
0 1 2
21 10 14
sol:
def convert(T,N):
L=T[-1]+T[0:-1]
Write a code in python for a function Convert ( Write a function SWAP2BEST ( ARR, Size) in
T, N) , which repositions python to modify the content of the list in such a
all the elements of array by shifting each of way that the elements, which are multiples of 10
them to next position and shifting first swap with the value present in the very
element to last position. next position in the list
e.g. if the content of array is
0 1 2 3
10 14 11 21
The changed array content will be:
0 1 2 3
14 11 21 10
'''

def convert(T,N):
L=T[1:]+T[0]

Write a function CHANGE( ) ,which accepts an Write function which accepts an integer array and size as
list of integer and its size as parameters and arguments and replaces elements having odd values with
divide all those list elements by 7 which are thrice its value and elements having even values with
divisible by 7 and multiply list elements by 3. twice its value.
Example : if an array of five elements
sol: initially contains elements as 3, 4, 5, 16, 9
The function should rearrange the content of the array as
d 9, 8, 15, 32,27
sol

Write a function which accepts an integer array Write a function which accepts an integer array and its
and its size as parameters and rearranges the size as arguments and swap the elements of every even
array in reverse. location with its following odd location.
Example: Example :
If an array of nine elements initially If an array of nine elements initially
contains the elements as 4, 2, 5, 1,6, 7, 8, 12, 10 contains the elements as
Then the function should rearrange the array as 2,4,1,6,5,7,9,23,10
10, 12, 8, 7, 6, 1, 5, 2, 4 then the function should rearrange the
array as 4,2,6,1,7,5,23,9,10
def rev(L,n):
mid=len(L)//2
j=len(L)-1
for i in range(mid):
L[i],L[j]=L[j],L[i]
j-=1
L=[4, 2, 5, 1,6, 7, 8, 12, 10]
rev(L,len(L))
print(L)
Write a user defined function findname(name) Write definition of a Method MSEARCH(STATES) to
where name is an argument in Python to display all the state names from a
delete phone number from a dictionary list of STATES, which are starting with alphabet M. For
phonebook on the basis of the name, where example: If the list STATES
name is the key. contains["MP","UP","WB","TN","MH","MZ","DL","
BH","RJ","HR"]
The following should get displayed MP MH MZ

Write a Get2From1( ) function in to transfer Identify the type one or more types of arguments in the
the content from one list ALL[ ] to two list following codes:
Odd[ ]and Even[]. a)
The Even should contain values from places def sum(a=4,b=6):
(0,2,4,………) of ALL[] and Odd[] return a+b
should contain values from places print (sum( )) Ans
( 1,3,5,……….). b)

''' def sum(a=1,b):


return a+b
print(sum(b=20, a=5 )) Ans
c)
def sum(*n):
for i in n:
total+=I
return total
print (sum(4,3,2,1,7,8,9)) Ans

d)
def sum(a=1,b):
return a+b
print(sum(10,20)) Ans

Consider the following function calls with


respect to the function definition.
Identify which of these will cause an error and
why?
i) calculate(12,3)
def calculate(a,b=5,c=10): Ans
return a*b-c
ii) calculate(c=50,35)
i) calculate(12,3) Ans
ii) calculate(c=50,35)
iii) calculate(20, b=7, a=15)
iv) calculate(x=10,b=12)
iii) calculate(20, b=7, a=15)
Ans

iv) calculate(x=10,b=12)
Ans.
find and write the output of the following python code:
(a) (b)
def change(p,q=20): def callme(n1=1,n2=2):
p=p+q n1=n1*n2
q=p-q n2+=2
print(p,'#',q) print(n1,n2)
return(p)
r=150 callme()
s=100 callme(2,1)
r=40 callme(3)
r=change(r,s)
print(r,'#',s)
s=change(s)

Ans Ans

(c) (d)
def show(x,y=2): def upgrade(a,b=2):
print(ord(x)+y) a=a+b
show('A') print(a+b)
show('B',3) i,j=10,20
upgrade(i,5)
Ans upgrade(i)

Ans

(e) (f) (g)


def func(a,b=5,c=10): x=1 def wish(message, num=1):
print(“a:”,a,” b:”,b, “ c:”,c) def cg(): print(message * num)
func(3,7) global x wish(‘Good’,2)
func(25,c=24) x=x+1 wish(“Morning”)
func(c=50, a=100) cg()
print(x) Ans
Ans
Ans

You might also like