0% found this document useful (0 votes)
291 views13 pages

Python Function Questions

Formal parameters are used in a function's header and define the inputs to the function. Actual parameters are used in function calls and send values from the calling function to the called function. A Python code example illustrates formal and actual parameters, where the formal parameter defines the input in the function header and the actual parameter sends a value in the function call statement.

Uploaded by

Tooba Mujeeb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
291 views13 pages

Python Function Questions

Formal parameters are used in a function's header and define the inputs to the function. Actual parameters are used in function calls and send values from the calling function to the called function. A Python code example illustrates formal and actual parameters, where the formal parameter defines the input in the function header and the actual parameter sends a value in the function call statement.

Uploaded by

Tooba Mujeeb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

COMPUTER SCIENCE WITH

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

Instead of writing code again te


call than once. If we
it later need to change th Code
in the form of a function and
more

Thus it saves our time also. we


change it in one place only.
library in modules.
i) Reusable functions can be put in a

the form of modules. These modules can ho


We can store the reusable functions in
:

nported
and used when needed in other programs.

the parts mentioned below


2 Fronn the program code given below, identify
def processNumber (x):
X = 72

return x +3

y 54
res = processNumber(y)

Identify these parts : function header, function call, arguments, parameters, function body, main program

Solution def processNumber (x):


Function header

Function call processNumber (y )


Arguments
Parameters X

Function body X = 72

return x + 3

Main program 54
res processNumber (y)

3. Trace the following code and predict output produced by it.

1. def power (b, p)


y = b ** p
2.
3. return y
4.
5. def calcSquare(x):
6. a
=power(x, 2)
7. return a
8.
WORKING WITH FUNCTIONS
Chopter 3:
129
9. n 5
10. result = calcSquare(n) + power (3, 3)

11. print(result)
Solution. Flow of execution for above code will be:

1 5 9 >10>5 >61-2>3671012 >3 >10 »11


output produced by above code will be:
The
52

4 Trace the flow of execution for following programs:

(a) 1 def power(b, p): 1. def increment (x) :


2 r =b** p 2. X X +1
3 return r 3.
4 4. # main program
5 def calcsquare(a) : 5. X = 3

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)

(c) 1. def increment (x) :


2. Z 45

. 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

call statement (7)nothing is


as
Solution. being retuned by increment()
(a) 1 5 >9 1 0 - > 5 >6>1 >2>3 >6->7>10>111
(6) 1>5 6 7 > 1 2 8 1+2>34>14-15>16

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

a suitable Python code to


illustrate both. alternative
Also, give which is used in function
call statemo.
names?
is a parameter,
ent to send the
Solution. Actual
Parameter
It is also
known as Argument. value
from calling function
to the called function. header of the called fume:

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)

addEm(6, 16, 26)

In the above code, actual parameters are 6, 16 and 26; and formal paraneters are x, y and -

6. Consider afunction with following header:

def info(object, spacing =


10, collapse =
1):
Here are some function cal!s given below. Find out which of these are correct and which of these are orrect

stating reasons
a.
info(obj1)
b. info(spacing = 20)

c. info( obj2, 12)


d. info( obji1, object = obj12)

e. info( obj3, collapse 0)


f. info()
g. info(collapse = 0, obj3 )

e. info( spacing = 15, object = obj4)

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

be missed. required argune


(c) Correct nd
Required parameter object gets its value as
obj2 ;
skipped argument collapse, default value 1 is spacing
for gets Va
taken.
(d) Incorrect Same
parameter object is given multiple values
ositional

one
ud
-

argument and one through


) Correct keyword(named) argument. and
Required paramete object gets its value as collapse gets
value 0
for
skipped argument spacing, default valueobj3;
10 is taken.
( Incorrect
kequired parameter object's value cannot be
g) Incorrect Positional arguments
skipped.
should be before
(h) Correct keyword argumen
Kequired argument iment.

object gets its value through a


Keywo
3: WORKING WITH FUNCTIONS
Chapter

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. ()

8. What will following code print ?


def addEm(x, y, z):
print(x+y+2)
def prod (x, y, z):
return x *y*z

addEm(6, 16, 26)


a

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

(i) def func (a = 1, b,C=2):


(i) def func (a = 1, b = 1, c= 2):
(iv) def func(a = 1, b = 1, c = 2, d):

will because non-default arguments


Solution. Function headers (i), (i) and (iv) cause error

cannot follow default arguments.


error.
Ohly function header (ii) will not cause any
suitable Python code to
What is the difference between a local variable and a global variable ? Also, give a

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.

def switch (x, y):


X, y y , x
print("inside switch:", end = ' ')

print ("x =", x, "y =", y)


X = 5

y 7

print("x =", x, "y =", y)


Global Environment
switch(x, y)
xC5
print("x =", X, "y =", y)

(
Local Environment
yG7 for switch()

Solution. The reason for un-reflected changes xC7 yCs


in the main program is that although both
main program and switch( ) have variables
with same names i.e, x and y, but their scopes
are different as shown in the adjacent figure.

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

print("inside switch:", end =' ')


print("x =", x, "y =", y)
X = 5

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)

Solution. The above code will produce an error.


The reason being whenever we assign something to a variable inside a function, the variable is

created as a local variable. Assignment creates a variable in Python.


Thus at line 2, when variable a is incremented with the passed value x, Python tries to create a local
variable a by assigning to it the value of expression on the right hand side of assignment. But
variable a also appears in the right hand side of assignment, which results in error because a is
undeclared so far in function.
To assign some value to a global variable from within a function, without creating a local variable
with the same name, global statement can be used. So, if we add
global 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

print (len (invaders) ==


0)
return max_level

res play ()
print(res)
Solution.
Global names invaders, pos, level, res

Local names max_level


Built in len
Predict the output of the following codefragment?
def func (message, num = 1):
print (message * num)

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.

18. What will be the output of following code?

def interest (prnc, time =2, rate =0.10)


r e t u r n (prnc * time * r a t e )

print(interest (6100, 1))


print(interest (5000, rate =0.e5))
print (interest (5000, 3, 0.12 ))
print (interest (time = 4, prnc = 5000))
Solution.
610.0
500.0
1800.0
2000.0
19. Is return statement
optional ? Compare and comment on the following two return statements
return
return val

Solution. The return statement is


optional ONLY WHEN the function is void or we ay
that when

function that returns a value, must have can say


the function does not return a value. A r e t u r n

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

# return the ones digit of the integer num


onesDigit =num % 10
return onesDigit
in
Write a function that receives an octal number and prints the equivalent number in other number bases i.e.,
21
decimal, binary and
hexadecimal equivalents.
Solution.

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

an octal number: "))


num =int(input("Enter
oct2others(num)
string-representations of
numbers but return the
do not return
bin() and hex()
Please recall that respectively.
hexadecimal number systems
and
equivalent numbers in binary returns
AP by providing
initial and step values to afunction that
Write a program that generates
4 terms ofan
irst four terms of the series.
Solutio
def retSeries (init, step ): init+3*step
init+2*step,
return init, init+step,

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

t4 retSeries (ini, st)


T, t2, t3,
=

print(t1, t2, t3, t4)


COMPUTER SCIENCE VITH PYTHON
136 - Xl

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

used inside a function to reter to


Parameter A name
value.
data and oten returns
a

Function Named subprogram that acts on

Actual Argument Argument


Actual Parameter Argument
Formal Parameter Parameter

Formal Argument Parameter


which particular piece ot code or a data value (e.g., variable) can be accae..
Scope Program part(s) in a

Assignment

Type A: Short Answer Questions/Conceptual Questions


1. A program functions is considered better than
having multiple designed a program without any
functions. Why ?
2. What all information does a function header give you about the function ?

3. What do you understand by flow of execution ?

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

Based Questions 137


pplication
B
Tpe
the
eors in following
the errors in codes ? Correct the code and
1.
What
are

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

1 def power(b, p):


y b ** p
2
return y
4
def calcSquare(x):
a = power (x, 2)

return a

9 n=5
10 result = calcSquare (n)

11 print(result)

3. What will the following function return


def addEm (x, y, 2):
print(x+y + z)
What will the following function print when called ?
def addEm(x, y, z):
return x + y + Z
print(x + y + z)
.What will be the output of following programs ?

1) num = 1 (i) num 1


def myfunc():
def myfunc ():
num 108
return num return num
print (num) print (num)
print (myfunc ()) print(myfunc())
print(num) print (num)
ii) num = 1
def myfunc (): def display (): '

global num end =


')
print("Hello",
num 10 display()
return num print("there! ")
print (num)
print(myfunc ())
print (num)
138 COMPUTER SCIENCE WITH PYTHHON
X
6. Predict the output of the following code

a 10
y 5

def myfunc():
a

a 2

print("y =", y, "a =", a)


print("a + y =", a +y)
return a + y

print("y =", y, "a =", a)


print(myfunc())
print("y =", y, "a =", a)

7. What is wrong with the following function definition


def addEm(x, y, z):
return x
+y +Z
print("the answer is", x + y + z)

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

print (number1, 'times, number2, '=, answer)


return(answer)
output multiply (5, 5)
) When the code above is executed, what prints out ?
(i) What is variable output equal to after the code is executed ?
10. 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)

(i) When the code above is executed, what gets printed ?


(ii) What is variable output equal to after the code is executed?
11. Find the in code below
errors
given :

(a) def minus(total, decrement)


output total decrement
print (output)
return (output)

(b) define check()


N input (Enter N: )
i = 3

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

9 def mean(a, b, c, d):


10 return float (sum (a, b, c, d))/length()
11.
12. print(sum(a, b, c,d), length(), mean(a, b, c, d))
13. Draw flow of execution for above program.
14. In the following code, which variables are in the same scope?

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

thefunction with these arguments


4, 6, 8, 2 +1, 4 3 *2,-32 the
of above function
and then write flow of execution for both
a
program with non-void version

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

(i) def increment(n):


n.append([49])
return n[e], n[1], n[2], n[3]
L [23, 35, 47]
m1, m2, m3, m4
= increment(L)

print(L)
print (m1, m2, m3, m4)
print(L[3] == m4)

Practice/Knowledge based Questions


Type C Programming
1. Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then retur
uns the
void and non-void forms.
amount converted to rupees. Create the function in both
2. Write a function to calculate volume of a box with appropriate default values for its parameters. Your

function should have the following input parameters:


(c) height of box.
(a) length of box; (b) width of box;
Test it by writing complete program to invoke it.

3. Write a program to have following functions:


() a function that takes a number as argument and calculates cube for it. The function does not
return a value. If there is no value passed to the function in function call, the function should
calculate cube of 2.
(ii) a function that takes two char arguments and returns True if both the arguments are equal
otherwise False.
Test both these functions by giving appropriate function call statements.
4. Write a function that receives two numbers and generates a random number from that range. Using this
function, the main program should be able to print three numbers randomly.
5. Write a function that receives two string arguments and checks whether they are same-length strings
(returns True in this case otherwise false).
6. Write a function namely nthRoot() that receives two parameters x and n and returns nth root of x ie,
x".

The default value of n is 2.


7. Write a function that takes a numbern and thern returns a
randomly generated number having exactuy n
digits (not starting with zero) e.g, if n is 2 then function can randomly return a number 10-99 but 07, 04
etc. are not valid two digit numbers.
8. Write function that takes two numbers and returns the number that has
a
minimum one's digit
[For example, if numbers passed are 491 and 278, then the function will return 491 because it has
minimum one's digit out of two given numbers
g
(491's 1 is < 278's 8)].
9. Write a program that series
generates a series using a function which takes first and last values or
and then generates four terms that are equidistant e.g., if two numbers passed are 1 and 7 theni function
returns 1 357.

You might also like