Python Function Questions
Python Function Questions
128 PYTHON X
Solved Prohlem
in a program ?
1. What is the significance of having functions
is very useful. It
offers following advant
Solution. Creating functions in programs ages
understand.
) The progran1 is easier to
becomes conmpact as the code of unctions is nnot
functions ot
part of it,
Main block of program thus is
understand.
easier to read and
is
(i) Redundant place, so making changes easier
code is at one
than once, we
when we need to use it more can . . .
nported
and used when needed in other programs.
return x +3
y 54
res = processNumber(y)
Identify these parts : function header, function call, arguments, parameters, function body, main program
Function body X = 72
return x + 3
Main program 54
res processNumber (y)
11. print(result)
Solution. Flow of execution for above code will be:
6 a = power(a, 2)
6. print(x)
return a 7. increment (x)
8 8. print(x)
9 n 5
10 result =calcSquare(n)
11 print (result)
. X = X+ 1
4. return x
5.
6. # main
7. y =3
8.
8. print(y)
9. y increment(y)
10. print (y)
11. q 77
12. print (q)
13. increment(q)
14. print(q)
15. print(x)
16. print(z) Control didnot return to function
10>11>12 >13>
C)1->7->89 1->2->3->4 9
COMPUTER SCIENCE WITH
130
and actual parameters? wn Nhat
PYTH
PYTHON-
are their
the formal parameters
5. What is the difference
between
Formal Parameter
is a parameter,
which is used in function
Parameter.
1ction to receiv the
It is also known as
value from actual parameter.
For example,
def addEm(x, y, z):
print(x +y + Z)
In the above code, actual parameters are 6, 16 and 26; and formal paraneters are x, y and -
stating reasons
a.
info(obj1)
b. info(spacing = 20)
Solution.
(a) Correct objl is for
positional parameter object; spacing gets 10
and
its default value
collapse gets its default value of 1.
(b) Incorrect
Required positional argument (object) missing; cannot
one
ud
-
131
7.
i s the default return value for function
a
that does not
return any value
(a) None (b) int (c) double explicitly ?
(d) null
Solution. ()
b prod (2, 3, 6)
print (a, b)
Solution.
None 36
9 In the previous question's code, identify the void and non-void functions. The previous code stores the return
values of both
void and non-void functions in variables. Why did Python not report an error when void
functions do not return a value?
Solution.
Void function addEm( )
Non-void function prod()
In Python, void functions do not return a value; rather they report the absence of returning value by
returning None, which is legal empty value in Python. Thus, variable a stores None and it is not any
error.
10. Consider below given function headers. ldentify which of these will cause error and why ?
) def func(a = 1, b):
illustrate both.
local variable and global variable are as given below:
Olution. The differences between a
Global Variable
Local Varlable
declared outside all
declared within a It is variable which is
1. It is a variable which is the functions
function or within a block
the program
function/block It is accessible throughout
within a
2. It is accessible only
in which it is declared
COMPUTER SCIEN
WITH
132
are global
variables and n and ct a
PYTHON-A
For example, in the following code, x, xCubed
def cube(n):
cn n * n *n
return Cn
X = 10
xCubed cube(x)
print(x, "cubed is", xCubed)
values of two variables through afunction,
but upon runmi
12. Following code intends to swap the switch() function but back again in mo:
the Code
te
swapped inside the main
output shows that the values are
program, the
variables remain un-suwapped. What could
be the reason? Suggest a remedy.
y 7
(
Local Environment
yG7 for switch()
The scope of r and y of suitch( ) is local. Though they are swapped in the namespace of suitchl ) but
their namespace is removed as soon as control returns to main program. The global variables r andy
remain unchanged as switch) worked with a different of copynot values with originalvalues
The remedy of above problem is that the switch( ) gets to work with global variables so that cnag
are made in the global variables. This can be done with the
help of global statement as shown be
def switch (x, y):
global x, yy
x, y =y, x
y=7
print("x =", X, "y =", y)
switch (x, y)
print("x =", x, "y=", y)
Now the above program will be
able to
swap the values of variables througn vitch(
(Though, now
passing parameter is redundant.) s
2WORKING WITH FUNCTIONS
Chopter 3 : WORK
133
codeinte to add a
given value to global variable a. What will the
13.
Following
following code produce?
1. def increase(x)
a a+X
2.
return
3.
4
a 20
6. b 5
7. increase (b)
8. print (a)
in the first line of function body, the above error will be corrected. Python won't create a local
variable a, rather will work with global variable a.
14. Which names are local, which are global and which are built-in in the following code fragment?
invaders =
'Big names
pos 20e
level =1
def play() :
max_level = level+ 10
res play ()
print(res)
Solution.
Global names invaders, pos, level, res
func('Python')
func( Easy', 3)
134 cOMPUTER SCIENCE WITH
PYTHON -XI
Solution.
Python
EasyEasyEasy
?
16. Predict the output of the following code fragment
defcheck(n1 1, = n2 2):
n1 n1+ n2
n2 + 1
print(n1, n2)
check()
check(2, 1)
check(3)
Solution.
3 3
3 2
5,3
17. What is the output of the following code?
a= 1
def f ():
= 10
print(a)
Solution. The code will print 1 to the console.
statement. at least
WITH FUNCTIONS
WORKING 135
C h a p t e r 3 : W O R K I N G
2
From given two return statements, statetement
return
returning any value, rather it returns the control to caller along with empty value None. And
is not.
the statement
return val
T i n g the control to caller along with the value contained in variable val.
1S
uea function that takes a positive integer and returns the one's position digit of the integer
20.
Solution.
def getOnes(num)
:
def oct2others( n)
print("Passedoctal number:", n)
numString =str(n)
decNum int( numString, 8)
Decimal: ", decNum)
print("Number in
bin(decNum))
print("Number in Binary:",
Hexadecimal: ", hex(decNum))
print("Number in
series: "))
of the AP
i n i t i a l value
n=
int (input ("Enter value of the
AP series: "))
as:")
St =
int(input ("Enter step value", st, "goes
ini, "& step
initial value",
print("Sseries with
GLOSSARY
statement.
function call
function in the
Argument A value provided to a
run.
during a program
The order of execution of statements
Flow of execution the value which was passed to it as an ae
Assignment
What are arguments ? What are parameters ? How are these two terms different yet related ? Give
example.
5. What is the of :
utility
) default arguments,
(i) keyword argumernts?
6.
Explain with a code
example the usage of default arguments and keyword
7. Describe the different styles of functions in arguments.
Python using appropriate examples.
8. Differentiate between fruitful functions and non-fruitful
functions.
9. Can a function return
multiple values ? How ?
10. What is scope ? What is the
scope resolving rule of Python ?
11. What is the difference
between local and global variables?
12. When is
global statement used ? Why is its use not
13. Write the term suitable for recommended ?
following descriptions
(a) A name inside the
parentheses of a function header that can receive a value.
(b) An argument passed to
specific parameter using the
a
(c)A value
passed to a function parameter. parameter name.
(d)A value
assigned to a parameter name in the function
(e)A value assigned to a parameter name in the header.
A name function call.
defined outside all function definitions.
(g) A variable created inside a function
body.
WORKING WITH FUNCTIONS
Choper : WORKIN
predict output:
total
=
0; (b) def Tot
(Number)
(a) arg2 ): #Method to find
def sum( arg1, Sum 0 Total
total arg1 arg2;
+
=
for C in
print("Total ", total)
Range (1, Number +1)
Sum += C
return total;
RETURN Sum
sum(10, 20);
print (Tot[3])
print("Total
: ", total) #Function Calls
print (Tot[6])
CBSE D 2015]
2
Considert
the following code and write the flow of execution for this. Line numbers have
been given
your reterence. for
return a
9 n=5
10 result = calcSquare (n)
11 print(result)
a 10
y 5
def myfunc():
a
a 2
8. Write a function namely fun that takes no parameters and always returns None.
9. Consider the code below and answer the questions that follow:
def multiply(number1, number2) :
answer = number1*number2
return(answer)
print(number1, 'times', number2, '="', answer
output = multiply (5,5)
answer = 1 + i ** 4 / N
Return answer
WORKING WITH FUNCTIONS
Chopler
alpha (n, ing = "xyz, k = 10) 139
) defa
return beta(string)
return nn
def beta (string)
return string = str(n)
Day"): )
print(alpha("Valentine's
= ' true
"))
print (beta (string
Orint (alpha(n 5, "Good-bye") :)
=
the entir environment, including all user-defined variables at the time line 10 is
12.
Draw
being executed
def sum(a, b, C, d ):
1.
result =
2.
result = result + a +b+ c +d
3.
return result
4.
5.
6. def length():
return 4
def func1():
a 1
b 2
def func2):
C 3
d 4
e 5
number that follows after it. Call
15. a
program with function that takes an integer and prints the
wnte a
programs.
What is the output of following code fragments
) def increment (n):
n.append([4])
return n
L [1, 2, 3]
M increment(L)
print (L, M)
cOMPUTER SCIENCE WITH
PYTHON
140
print(L)
print (m1, m2, m3, m4)
print(L[3] == m4)