[go: up one dir, main page]

100% found this document useful (1 vote)
102 views19 pages

01 Working With Function

The document discusses functions in Python. It contains multiple choice questions about functions that cover topics like parameters, arguments, scope, returning values, and more. The questions help to test understanding of key concepts related to defining and using functions.

Uploaded by

imshreyarajput
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
100% found this document useful (1 vote)
102 views19 pages

01 Working With Function

The document discusses functions in Python. It contains multiple choice questions about functions that cover topics like parameters, arguments, scope, returning values, and more. The questions help to test understanding of key concepts related to defining and using functions.

Uploaded by

imshreyarajput
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/ 19

Working with Functions

MCQs
1. What is the default return value for a function that does not return a
value explicitly?
(a) None (b) int
(c) double (d) null

2. Which of the following items are present in the function header


(a) function name only
(b) both function name and parameter list
(c) parameter list only
(d) return value

3. What of the following keywords marks the beginning of the function


block?
(a) func (b) define
(c) def (d) function

4. Name the statement that sends back a value from a function.


(a) print (b) input
(c) return (d) None

4. What is the name given to that are of memory where the system stores
the parameters and local variable of a function call?
(a) a heap (b) storage area
(c) a stack (d) an array

5. Pick one the following statements to correctly complete the function


body in the given code snippet.
def f(number):
# Missing function body
print(f(5))
(a) return "number" (b) print(number)
(c) print("number") (d) return number

6. Which of the following function headers is correct?


(a) def f(a = 1, b): (b) def f(a = 1, b, c = 2):
(c) def f(a = 1, b = 1, c = 2): (d) def f(a = 1, b = 1, c = 2, d):

7. Which of the following statements is not true for parameter passing to


functions?
(a) You can pass positional arguments in any order.
(b) You can pass keyword arguments in any order.
(c) You can call a function with positional and keyword arguments.
(d) Positional arguments must be before keyword arguments in a function
call.

8. Which of the following statement is not true in context of positional


and default parameters in Python functions?
(a) Default parameters must occur to the right of Positional parameters.
(b) Positional parameters must occur to the right of default parameters.
(c) Positional parameters must occur to the left of Default parameters.
(d) All parameter to the right of a Default parameter must also have Default
values.

9. Which of the following is not correct in context of scope of variables?


(a) global keyword is used to change value of a global variable in a local
scope.
(b) local keyword is used to change the value of a local variable in a
global scope.
(c) Global variables can be accessed without the global keyword in a local
scope.
(d) Local variables cannot be used outside its scope.

10. Which of the following function calls can be used to invoke the below
function definition?
def test(a, b, c, d)
(a) test(1, 2, 3, 4) (b) test(a = 1, 2, 3, 4)
(c) test(a = 1, b = 2, c = 3, 4) (d) test(a = 1, b = 2, c = 3, d = 4)

11. Which of the following function calls will cause Error while invoking
the below function definition?
def test(a, b, c, d)
(a) test(1, 2, 3, 4) (b) test(a = 1, 2, 3, 4)
(c) test(a = 1, b = 2, c = 3, 4) (d) test(a = 1, b = 2, c = 3, d = 4)

12. For a function header as follows:


def Calc(x,y=20):
Which of the following function call will give an error.
(a) Calc (15,25) (b) Calc (x = 15, y = 25)
(c) Calc ( y = 25) (d) Calc ( x = 25)

13. What is a variable defined inside a function referred to as


(a) A static variable (b) A global variable
(c) A local variable (d) An automatic variable

14. What is a variable defined outside all the functions referred to as?
(a) A static variable (b) A global variable
(c) A local variable (d) An automatic variable
15. Carefully observe the code and give the answer.
def function1(a):
a= a + '1'
a=a*2
>>> function1("hello")
(a) indentation Error
(b) cannot perform mathematical operation on strings
(c) hello2
(d) hello2hello2

16. What is the result of this code?


def print_double(x):
print(2 ** x)
print_double(3)
(a) 8 (b) 6
(c) 4 (d) 10

17. What is the order of resolving scope of a name in a Python program?


(L: Local namespace, E : Enclosing namespace, B: Built-In Namespace, G:
Global namespace)
(a) BGEL (b) LEGB
(c) GEBL (d) LBEG

18. Which of the given argument types can be skipped from a function
call?
(a) positional arguments (b) keyword arguments
(c) named arguments (d) default arguments

Extras
19. Functions that do not return any value are known as:
(a) fruitful functions (b) void functions
(c) library functions (d) user-defined functions

20. A variable created or defined within a function body is classified as:


(a) local (b) global
(c) built-in (d) instance

21. Which of the following arguments works with implicit values that are
used if no value is provided?
(a) keyword (b) required
(c) variable-length (d) default

22. Which values are used by the functions to communicate information


back to the caller?
(a) local (b) global
(c) return (d) random
23. What is the output of the program given below?
x = 50
def func (x) :
x=2
func (x)
print ('x is now', x)
(a) x is now 50 (b) x is now 2
(c) x is now 100 (d) Error

Type A Questions
1. What is a function?
Ans. A function is a set of instructions or subprograms that are used to fulfil
the user’s need. In other words, a function is a bunch of code which
performs a specific task.
2. Why do programmers need functions in python programming?
Ans.
(a) To make the program easy
(b) Divide the large program into a small block of codes
(c) Reduce the lines of code
(d) Easy to update
3. Write the types of functions supported by Python.
Ans. There are three types of functions supported by python.
(a) Built-in functions.
(b) Function defined in modules.
(c) Functions defined by user(User defined functions).
4. What is the local variable and global variable? Explain with an
example.
Ans.
Global Variable: A variable that is declared in top-level statements is called
a global variable. To access the value of a global variable user need to write
a global keyword in front of the variable in a function.
Local Variable: A name declared in a specific function body is called a local
variable
5. What are the arguments supported by python? Explain each of them
with a suitable example.
Ans. Python supports four argument types:
(a) Positional Arguments: Arguments passed to a function in correct
positional order, no. of arguments must match with no. of parameters
required.
(b) Default Arguments: Assign a default value to a certain parameter, it is
used when the user knows the value of the parameter, default values are
specified in the function header. It is optional in the function call statement.
If not provided in the function call statement then the default value is
considered. Default arguments must be provided from right to left.
(c) Key Word Arguments: Keyword arguments are the named arguments
with assigned values being passed in the function call statement, the user
can combine any type of argument.
(d) Variable Length Arguments: It allows the user to pass as many
arguments as required in the program. Variable-length arguments are
defined with the * symbol.

6. What are the parts of functions? Explain with a suitable example.


Ans. The arts of functions are as follows:
(a) Function header: It starts with def followed by the function name and
required parameters. Parameters are the input variables written into
brackets. These parameters are supplied in the function calling statement.
(b) Function Body: This is the main part of a program. It contains the main
block of the program. The set of instructions such as calculations, logical
comparisons etc is written here in this part. It ends with a return statement.
Indentation is very important for the function body.
(c) Function calling statement: This is the final part of a function. It invokes
the function and returns the output as instructed into the function body.

7. Write and explain the types of functions supported by python.


Ans.
(a) Built in Functions: Pre-defined functions of python such as len(), type(),
input() etc.
(b) Functions defined in modules: Functions defined in particular modules,
can be used when the module is imported. A module is a container of
functions, variables, constants, classes in a separate file which can be reused.
(c) User Defined Functions: Function created by the programmer

8. Write the ways of import module in the python program.


Ans. The module can be imported in two ways
(a) import statement: Used to import the entire module. EX. import math
(b) from statement : import all functions or the selected one. EX. from
random import randint

9. Differentiate between parameters and arguments.


Ans.
Parameters Arguments

These are specified during the Values passed during the function call.
function definition.

They are also known as formal They are also known as actual
parameters. parameters.
Parameters Arguments

The values passed as parameters are Every argument is assigned to a


local variables and are assigned parameter when the function is
values of the arguments during the defined.
function call.

These variables help in the complete These variables are passed to the
execution of the function. function for execution.

The values contained by these The arguments are accessible


parameters can only be accessed from throughout the program depending
function return statements or if the upon the scope of the variable
scope of these parameters is made assigned.
global.

Type B Questions
1. What are the errors in following codes? Correct the code and predict
output:
(a)
total = 0 ;
def sum( arg1, arg2 ):
total = arg1 + arg2 ;
print("Total :", total)
return total ;
sum( 10, 20 ) ;
print("Total :", total)
Ans. This code contains following errors.
1. There should not be indentation in line 2 ‘def sum(arg1, arg2):’.
2. There should be one indent in line 5 ‘return total’
3. There should be no semi-column at the end of line 1, 5 and 6.
The correct code is as follows:
total = 0
def sum(arg1, arg2):
total = arg1 + arg2
print("Total :",total)
return total
sum(10,20)
print("Total :",total)
output:
Total : 30
Total : 0
(b)
def Tot (Number) #Method to find Total
Sum = 0
for C in Range (1, Number + 1):
Sum += C
RETURN Sum
print (Tot[3]) #Function Calls
print (Tot[6])

Ans. This code contains following errors.


1. In line 1, at the time of function definition colon is missing.
2. In line 4, double indentation is required.
3. In line 5, RETURN should be written as return and Range should be
written as range because Python is a case sensitive language
4. In line 6 and 7, instead of brackets, parenthesis will be used.
The correct code is as follows.
def Tot (Number): #Method to find Total
Sum = 0
for C in range (1, Number + 1):
Sum += C
return Sum
print (Tot(3)) #Function Calls
print (Tot(6))
Output:
6
21
2. Find and write the output of the following code.
def call(P = 40, Q= 20 ):
P = P + Q
Q = P - Q
print(P,'@',Q)
return P
R = 200
S = 100
R = call(R, S)
print(R,'@',S)
S = call(S)
print(R,'@',S)
Ans.
Output.
300 @ 200
300 @ 100
120 @ 100
300 @ 120
3. Consider the following code and write the flow of execution for this.
Line numbers have been given for your reference.
def power(b, p):
y = b**p
return y
def calcSquare(x):
a = power(x, 2)
return a
n = 5
result = calcSquare(n)
print(result)
Ans. Output.
25
4. What will the following function return?
def addEm(x,y,z):
print(x+y+z)
Ans. This function will return none as there is no return value in the
function definition.
5. What will be following function print when called?
def addEm(x,y,z):
return x+y+z
print(x+y+z)
Ans. The following function will not print anything because the print
statement is written after the return statement and will be skipped.
However if we print the value of addEm function then it will print the value
of x+y+z.
6. What will be the output of the following program?
(i)
num = 1
def myfunc():
return num
print(num)
print(myfunc())
print(num)
Ans. Output.
1
1
1
(ii)
num = 1
def myfunc():
num = 10
return num
print(num)
print(myfunc())
print(num)
Ans. Output:
1
10
1
(iii)
num = 1
def myfunc():
global num
num = 10
return num
print(num)
print(myfunc())
print(num)
Ans. Output.
1
10
10
(iv)
def display():
print("Hello",end =' ')
display()
print("there")
Ans. Output.
Hello there
7. Predict the output of the following code?
a = 10
y = 5
def myfunc():
y = 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)
Ans. It will show an error because of local variable a being declared after the
value assignment to y in line 4.
8. What is wrong with the following function definition?
def addEm(x,y,z):
return x + y + z
print("The answer is:",x+y+z)
Ans. in line 2, the return statement is placed at a wrong place because the
interpreter will not read the lines in the function block after the return
statement. So the correct program should be
def addEm(x,y,z):
print("The answer is:",x+y+z)
return x + y + z
9. Write a function namely fun that takes no parameters and always
returns None.
Ans.
def fun():
print("This function will return None.")
return

10 .Consider the code below and answer the following question.


def multiply(number1, number2):
answer =number1*number2
print(number1,'times',number2,'=',answer)
return(answer)
output = multiply(5,5)
(i) When the code above is executed, what prints out?
Ans. it gives the output: 5 times 5 = 25
(ii) What is the variable output equals to after the code is executed?
Ans. The variable output equals to 25 after the code executed.
11. Consider the code below and answer the following question.
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 prints out?
Ans. Nothing will print out because the print statement is after the return
statement and interpreter will skip the lines/statements after the return
statement.
(ii) What is the variable output equals to after the code is executed?
Ans. The variable output equals to 25 after the code executed.
12. Find the errors in the code given below.
(a)
def minus(total, decrement)
output = total - decrement
print(output)
return (output)
Ans. In line 1, there is no colon at the end of line.
(b)
define check()
N = input('Enter N:')
i = 3
answer = 1 + i ** 4 / N
Return answer
Ans.
1. In line 1 there is no colon at the end of line.
2. In line 2, N will store string and it cannot be used in division in line 4.
3. In line 5, Return should be written in lowercase as return as python is case
sensitive.
(c)
def alpha(n,string =='xyz', k= 10):
return beta(string)
return n
def beta(string)
return string ==str(n)
print(alpha("Valentine's Day"):)
print(beta(string = 'true'))
print(alpha(n=5,"Good-bye"):)
Ans.
1. In line one assignment operator will be used instead of comparison
operator (equal to). Inside alpha function definition there are two return,
however it will skip the second statement and will not show any error.
2. In line 4, at the beta function definition, a colon is needed.
3. in line 6 and line 8 there will no colon after the parenthesis, we can
however use them inside the argument as string.
4. In line 8 keyword argument will be used after the positional argument.
13. 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
Ans.
Here a, b, c, d are in same scope i.e. local scope.
14. What is the output of the following code fragments?
(i)
def increment(n):
n.append([4])
return n
L = [1,2,3]
M = increment(L)
print(L,M)
Ans. Output:
[1, 2, 3, [4]] [1, 2, 3, [4]]
(ii)
def increment(n):
n.append([49])
return n[0],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)
Ans. Output
[23, 35, 47, [49]]
23 35 47 [49]
True
(iii)

Ans. Output: 100

Board Pattern Questions


1. Write a function LShift(Arr,n) in Python, which accepts a list Arr of
numbers and n is a numeric value by which all elements of the list are
shifted to left. Sample Input Data of the list Arr= [ 10,20,30,40,12,11], n=2
Output:
Arr = [30,40,12,11,10,20]
2. Write a function INDEX_LIST(L), where L is the list of elements passed
as argument to the function. The function returns another list named
‘indexList’ that stores the indices of all Non-Zero Elements of L. For
example: If L contains [12,4,0,11,0,56] The indexList will have - [0,1,3,5]

Q3. Write a function countNow(PLACES) in Python, that takes the


dictionary, PLACES as an argument and displays the names (in
uppercase)of the places whose names are longer than 5 characters. For
example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
Or

Q4. Write a function, lenWords(STRING), that takes a string as an


argument and returns a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the tuple will
have (4, 3, 2, 4, 4, 3)
Or

Q5. Write a function Vowels (LIST) in Python, which accepts a list LIST
of strings. Return a list containing only those strings which starts with a
vowel. Sample Input Data of the list
LIST= [“it”, ”is”, ”over”, ”Anakin”, ”I”, ”have”, ”high”, ”ground”]
NEWLIST = [“it”, “is”, “over”, “Anakin”, ”I”]
6. Write a generator function generatesq() that displays the squareroots of
numbers from 100 to n where n is passed as an argument.

7. Write a user defined function findname(name) where name is an


argument in Python to delete phone number from a dictionary
phonebook on the basis of the name ,where name is the key.

8. Write a generator function to generate odd numbers between a and


b(including b).Note: a and b are received as an argument by the function.
9. Write a function COUNT(STRING), in which function takes a string
STRING as an argument and returns the number of words in the string.
For example if the Content of String are: “Honesty is the best Policy”
The function should return 5.

10. Write a Function LONGEST(STRING) which takes a string


“STRING” as an argument and returns the longest string.
11. Write a function RECORD(DICT) in python which takes a dictionary
DICT as an argument and returns the marks of the student whose Key is
103.
For example if DICT = {101 : [“ABHISHEK”,34], 102 : [“ABHIMAYU”,48],
103 : [“BHAVNA”,45], 104 : [“CHAYA”,23]}
The function should return 45

12. Write a function RECORD(DICT) in python which takes a dictionary


DICT as an argument and returns the name of the student in lower case
whose Key is 102.
For example if DICT = {101 : [“ABHISHEK”,34], 102 : [“ABHIMAYU”,48],
103 : [“BHAVNA”,45],
104 : [“CHAYA”,23]}
The function should return “abhimanyu”

You might also like