Working on Function
WORKING
ON FUNCTIONS
A. Multiple
Choice Questions.
Q1. If return
statement is not used inside the function, the function will return:
(a) 0
(b) None object
(c) an arbitrary integer (d) Error! Functions must have
a return statement.
Q2. Which of
the following keywords marks the beginning of the function block?
(a)
func (b) define
(c)
def (d) function
Q3. What is the area of memory
called, which stores the parameters and local variables of a function call?
(a)
a heap (b) storage area
(c) a stack (d)
an array
def func2(): print(2 + 3) |
def main() print ("hello") |
(a) (b)
square (a) return a * a
|
def compute(): print (x * x)
|
(c) (d)
Answer
(a) Colon is missing at the end of
function header.
(b) There is no error.
(c) The variable x is not defined.
(d) def keyword at the beginning and
colon at the end of function header are missing.
B. Multiple
Choice Questions
Q1. What is the
default return value for a function that does not return any value explicitly ?
a. None b.
int
c.
double d.
null
Q2. 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
Q3. Which of
the following keywords marks the beginning of the function block?
a. func b. define
c.
def d. function
Q4. What is the name given to that
area of memory, where the system stores the parameters and local variables of a
function call?
a. a heap b. storage area
c. a stack d. an array
Q5. 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
Q6. 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):
Q7. 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.
Q8. Which of the following is not
correct 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 parameters to the right of a
Default parameter must also have Default values.
Q9. 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 value of a local variable in a global scope.
c. Global variables can be accessed
without using the global keyword in a local scope.
d. Local variables cannot be used
outside its scope.
Q10. 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)
Q11. 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)
Q12. For a
function header as follows: def Calc(X,Y
= 20):
Which of the
following function calls will give an error?
a. Calc(15, 25) b. Calc(X =
15, Y = 25)
c. Calc(Y = 25) d.Calc(X = 25)
Q13. 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
Q14. 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
Q15. 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
Q16. What is
the result of this code?
def print_double(x):
print(2 ** x)
print_double(3)
a. 8 b. 6
b. 4 d. 10
Q17. What is
the order of resolving scope of a name in a Python program ?
a. B G E L b. L
E G B
c. G E B L d. L B E G
Q18. 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
C. Fill
in the Blanks
Q1. A function
is a subprogram that acts on data and often returns a value.
Q2. Python
names the top level segment (main program) as __main__.
Q3. In Python,
program execution begins with first statement of __main__ segment.
Q4. The values
being passed through a function-call statement are called arguments / actual parameters / actual arguments.
Q5. The values
received in the function definition/header are called parameters / formal parameters / formal arguments.
Q6. A parameter
having default value in the function header is known as a default parameter.
Q7. A default argument can be skipped in the function
call statement.
Q8. Keyword arguments are the named arguments with
assigned values being passed in the function call statement.
Q9. A void
function also returns a None value to its
caller.
Q10. By
default, Python names the segment with top-level statements (main program) as __main__.
Q11. The flow of execution refers
to the order in which statements are executed during a program run.
Q12. The
default value for a parameter is defined in function header.
D. State
True or False.
Q1. Non-default
arguments can be placed before or after a default argument in a function
definition. F
Q2. A parameter
having default value in the function header is known as a default parameter. T
Q3. The first
line of function definition that begins with keyword def and ends with a colon
(:), is also known as function header. T
Q4.Variables
that are listed within the parentheses of a function header are called function
variables.
F
Q5. In Python,
the program execution begins with first statement of __main__ segment. T
Q6. Default
parameters cannot be skipped in function call. F
Q7. The default
values for parameters are considered only if no value is provided for that
parameter in the function call statement. T
Q8. A Python
function may return multiple values. T
Q9. A void
function also returns a value i.e., None to its caller. T
Q10. Variables
defined inside functions can have global scope. F
Q11. A local variable
having the same name as that of a global variable, hides the global variable in
its function. T
E. Assertions
and Reasons
Q1. Assertion.
A function is a subprogram.
Reason. A
function exists within a program and works within it when called.
Answer: (a) Both
Assertion and Reason are true and Reason is the correct explanation of
Assertion.
Explanation: A function is a
subprogram that acts on data and often returns a value. It is a self-contained
unit of code that performs a specific task within a larger program. Functions
are defined within a program and can be called upon to execute a specific set
of instructions when needed.
Q2. Assertion.
Non-default arguments cannot follow default arguments in a function call.
Reason. A
function call can have different types of arguments.
Answer (b) Both
Assertion and Reason are true but Reason is not the correct explanation of
Assertion.
Explanation: In a function call,
any parameter cannot have a default value unless all parameters appearing on
its right have their default values. Hence, non-default arguments cannot follow
default arguments in a function call. Python supports three types of formal arguments:
(a)
Positional arguments (b) Default arguments (c) keyword arguments
Q3. Assertion.
A parameter having a default in function header becomes optional in function
call.
Reason. A
function call may or may not have values for default arguments.
Answer: (a) Both
Assertion and Reason are true and Reason is the correct explanation of
Assertion.
Explanation: When a parameter
in a function header has a default value, it means that if no value is provided
for that parameter during the function call, the default value will be used.
This effectively makes the parameter optional in the function call. When
calling a function with default arguments, we have the option to either provide
values for those arguments or omit them, in which case the default values will
be used.
Q4. Assertion:
A variable declared inside a function cannot be used outside it.
Reason: A
variable created inside a function has a function scope.
Answer: (a) Both
Assertion and Reason are true and Reason is the correct explanation of
Assertion.
Explanation: Variables
declared inside a function are typically local to that function, meaning they
exist only within the scope of the function and they can only be accessed and
used within the function in which they are declared.
Q5. Assertion:
A variable not declared inside a function can still be used inside the function
if it is declared at a higher scope level.
Reason: Python
resolves a name using LEGB rule where it checks in Local (L), Enclosing (E),
Global (G) and Built-in scopes (B), in the given order.
Answer: (a) Both
Assertion and Reason are true and Reason is the correct explanation of
Assertion.
Explanation: In Python, if a
variable is not declared inside a function but is declared at a higher scope
level (e.g., in the global scope or an enclosing scope), the function can still
access and use that variable. Since Python follows the LEGB rule, variables declared
at higher scope levels can be accessed within functions.
Q6. Assertion:
A parameter having a default value in the function header is known as a default
parameter.
Reason: The
default values for parameters are considered only if no value is provided for
that parameter in the function call statement.
Answer: (b) Both
Assertion and Reason are true but Reason is not the correct explanation of
Assertion.
Explanation: A
default parameter is a parameter in a function definition that has a predefined
value. When we call a function with default parameters, if we don't provide a
value for a parameter, the default value specified in the function header will
be used instead.
Q7. Assertion: A function declaring a variable
having the same name as a global variable, cannot use that global variable.
Reason: A local
variable having the same name as a global variable hides the global variable in
its function.
Answer: (a) Both
Assertion and Reason are true and Reason is the correct explanation of
Assertion.
Explanation: Inside a function, you assign a value to a
name which is already there in global scope, Python won't use the global scope
variable because it is an assignment statement and assignment statement creates
a variable by default in current environment. That means a local variable
having the same name as a global variable hides the global variable in its
function.
Question8.
Assertion: If
the arguments in a function call statement match the number and order of
arguments as defined in the function definition, such arguments are called
positional arguments.
Reason: During
a function call, the argument list first contains default argument(s) followed
positional argument(s).
Answer: (c) Assertion
is true but Reason is false.
Explanation: If
the arguments in a function call statement match the number and order of
arguments as defined in the function definition, such arguments are called
positional arguments. During a function call, the argument list first contains
positional argument followed by default arguments because any parameter cannot
have a default value unless all parameters appearing on its right have their
default values.
Type
A: Short Answer Questions/Conceptual Questions
Q1. A program
having multiple functions is considered better designed than a program without
any functions. Why?
Ans. A program having multiple functions is
considered better designed than a program without any functions because it
makes program handling easier as only a small part of the program is dealt with
at a time, thereby avoiding ambiguity. It reduces program size make the program
more readable and understandable to a programmer thereby making program
management much easier.
Q2. What all
information does a function header give you about the function?
Ans. Function header is the first line of function
definition that begins with keyword def and ends with a colon (:), specifies
the name of the function and its parameters.
Q3. What do you
understand by flow of execution?
Ans. Flow of
execution refers to the order in which statements are executed during a program
run.
Q4. What are arguments?
What are parameters? How are these two terms different yet related? Give
example.
Ans. Arguments — The values being passed through a
function-call statement are called arguments.
Parameters —
The values received in the function definition/header are called parameters.
Arguments
appear in function call statement whereas parameters appear in function header.
The two terms are related because the values passed through arguments while
calling a function are received by parameters in the function definition.
For example:
def multiply(a, b):
print(a *
b)
multiply(3, 4)
Here,
a and b are parameters while 3, 4 are arguments.
Q5. What is the
utility of: (i) default arguments, (ii) keyword arguments?
Ans. (i) Default arguments — Default arguments are
useful in case a matching argument is not passed in the function call
statement. They give flexibility to specify the default value for a parameter
so that it can be skipped in the function call, if needed. However, still we
cannot change the order of the arguments in the function call.
(ii) Keyword
arguments — Keyword arguments are useful when you want to specify arguments by
their parameter names during a function call. This allows us to pass arguments
in any order, as long as we specify the parameter names when calling the
function. It also makes the function call more readable and self-explanatory.
Q6. Explain
with a code example the usage of default arguments and keyword arguments.
Ans. Default arguments — Default arguments are
used to provide a default value to a function parameter if no argument is
provided during the function call.
Output Hello Alice Hi there Bob |
def greet(name, message="Hello"):
print(message, name)
greet("Alice")
greet("Bob", "Hi there")
In this
example, the message parameter has a default value of "Hello". If no
message argument is provided during the function call, the default value is
used.
Output Alice
is 25 years old and lives in New York Bob
is 30 years old and lives in London Hi there Bob |
def
person(name, age, city):
print(name, "is", age,
"years old and lives in", city)
person(age=25,
name="Alice", city="New York")
person(city="London",
name="Bob", age=30)
In this
example, the arguments are provided in a different order compared to the
function definition. Keyword arguments specify which parameter each argument
corresponds to, making the code more readable and self-explanatory.
Both default
arguments and keyword arguments provide flexibility and improve the readability
of code, especially in functions with multiple parameters or when calling
functions with optional arguments.
Q7. Describe
the different styles of functions in Python using appropriate examples.
Ans. The
different styles of functions in Python are as follows:
Built-in
functions: These are
pre-defined functions and are always available for use.
Example:
name = input("Enter your
name: ")
name_length = len(name)
print("Length of your
name:", name_length)
In the above example, print(),
len(), input() etc. are built-in functions.
User
defined functions: These
are defined by programmer.
Example:
def calculate_area(length,
width):
area = length * width
return area
length = 5
width = 3
result = calculate_area(length,
width)
print("Area of the
rectangle:", result)
In
the above example, calculate_area is a user defined function.
Functions
defined in modules: These
functions are pre-defined in particular modules and can only be used when
corresponding module is imported.
Example:
import math
num = 16
square_root = math.sqrt(num)
print("Square root
of", num, ":", square_root)
In
the above example, sqrt is a function defined in math module.
Q8. Differentiate
between fruitful functions and non-fruitful functions.
Ans.
Fruitful functions |
Non-fruitful functions |
Functions returning some value are
called as fruitful functions. |
Functions that do not return any
value are called as non-fruitful functions. |
They are also called as non-void
functions. |
They are also called as void
functions. |
They have return statements in the
syntax: return<value>. |
They may or may not have a return
statement, but if they do, it typically appears as per syntax: return. |
Fruitful functions return some
computed result in terms of a value. |
Non-fruitful functions return
legal empty value of Python, which is None, to their caller. |
Q9. Can a
function return multiple values? How?
Ans. Yes, a
function can return multiple values. To return multiple values from a function,
we have to ensure following things:
1. The return
statement inside a function body should be of the form:
return
<value1/variable1/expression1>,<value2/variable2/expression2>,....
2. The function
call statement should receive or use the returned values in one of the
following ways:
(a) Either it receives the returned values in
form a tuple variable.
(b) Or we can directly unpack the received values of tuple
by specifying the same number of variables on the left-hand side of the
assignment in function call.
Q10. What is scope?
What is the scope resolving rule of Python?
Ans. Scope
refers to part(s) of program within which a name is legal and accessible. When
we access a variable from within a program or function, Python follows name
resolution rule, also known as LEGB rule. When Python encounters a name
(variable or function), it first searches the local scope (L), then the
enclosing scope (E), then the global scope (G), and finally the built-in scope
(B).
Q11. What is
the difference between local and global variable?
Ans.
Local
variable |
Global
variable |
A local variable is a variable
defined within a function. |
A global variable is a variable
defined in the 'main' program. |
They are only accessible within
the block in which they are defined. |
They are accessible from anywhere
within the program, including inside functions. |
These variables have local scope. |
These variables have global scope |
The lifetime of a local variable
is limited to the block of code in which it is defined. Once the execution
exits that block, the local variable is destroyed, and its memory is
released. |
Global variables persist
throughout the entire execution of the program. They are created when the
program starts and are only destroyed when the program terminates. |
Q12. When is
global statement used? Why is its use not recommended?
Ans. If we want
to assign some value to the global variable without creating any local variable
then global statement is used. It is not recommended because once a variable is
declared global in a function, we cannot undo the statement. That is, after a
global statement, the function will always refer to the global variable and
local variable cannot be created of the same name. Also, by using global
statement, programmers tend to lose control over variables and their scopes.
Q13. Write the
term suitable for following descriptions:
(a) A name
inside the parentheses of a function header that can receive a value. Parameter
(b) An argument
passed to a specific parameter using the parameter name. Keyword
argument
(c) A value
passed to a function parameter.
Argument
(d) A value
assigned to a parameter name in the function header. Default value
(e) A value
assigned to a parameter name in the function call. Keyword argument
(f) A name
defined outside all function definitions.
Global variable
(g) A variable
created inside a function body. Local variable
Q14. What do
you understand by local and global scope of variables? How can you access a
global variable inside the function, if function has a variable with same name?
Ans. Local scope — Variables defined within a specific
block of code, such as a function or a loop, have local scope. They are only
accessible within the block in which they are defined.
Global
scope — Variables defined outside of any
specific block of code, typically at the top level of a program or module, have
global scope. They are accessible from anywhere within the program, including
inside functions.
To access a
global variable inside a function, even if the function has a variable with the
same name, we can use the global keyword to declare that we want to use the
global variable instead of creating a new local variable. The syntax is:
global<variable
name>
For example:
def state1():
global
tigers
tigers =
15
print(tigers)
tigers = 95
print(tigers)
state1()
print(tigers)
In the above
example, tigers is a global variable. To use it inside the function state1 we
have used global keyword to declare that we want to use the global variable
instead of creating a new local variable.
Type B: Application Based Questions
Q1(a). What are
the errors in following codes? Correct the code and predict output:
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 |
def sum(arg1,
arg2): Ans.
total = arg1 +
arg2;
print("Total :", total)
return total;
sum(10, 20);
print("Total :", total)
Explanation: There is an
indentation error in second line. The return statement should be indented
inside function and it should not end with semicolon. Function call should not
end with semicolon.
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)) |
def Tot(Number) #Method to find
Total Ans.
Sum = 0
for C in Range (1, Number + 1):
Sum += C
RETURN Sum
print (Tot[3]) #Function Calls
print (Tot[6])
Output
6
21
Explanation: There should be
a colon (:) at the end of the function definition line to indicate the start of
the function block. Python's built-in function for generating sequences is
range(), not Range().Python keywords like return should be in lowercase. When
calling a function in python, the arguments passed to the function should be
enclosed inside parentheses () not square brackets [].
Q2. Find and
write the output of the following python code:
Answer
Output 300
@ 200 300
@ 100 120
@ 100 300
@ 120 |
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)
Q3. Consider
the following code and write the flow of execution for this. Line numbers have
been given for your reference.
1. def power(b, p):
2. y = b ** p
3. return y
4.
5. def calcSquare(x):
6. a = power(x, 2)
7. return a
8.
9. n = 5
10. result = calcSquare(n)
11. print(result)
Ans. The flow
of execution for the above program is as follows:
1 → 5 → 9 → 10
→ 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11
Q4. What will
the following function return?
def addEm(x, y, z):
print(x + y +
z)
Answer: The
function addEm will return None. The provided function addEm takes three
parameters x, y, and z, calculates their sum, and then prints the result.
However, it doesn't explicitly return any value. In python, when a function
doesn't have a return statement, it implicitly returns None. Therefore, the
function addEm will return None.
Q5. What will
the following function print when called?
def addEm(x, y, z):
return x + y + z
print(x + y + z)
Ans. The
function addEm prints nothing when called.
Explanation: The function
addEm(x, y, z) takes three parameters x, y, and z. It returns the sum of x, y,
and z. Since the return statement is encountered first, the function exits
immediately after returning the sum. The print statement after the return
statement is never executed. Therefore, it prints nothing.
Answer:
Output 1 1 1 |
num = 1
def myfunc():
return num
print(num)
print(myfunc())
print(num)
Explanation: The code
initializes a global variable num with 1. myfunc just returns this global
variable. Hence, all the three print statements print 1.
Question 6(ii) What
will be the output of following program?
Answer:
Output 1 10 1 |
def myfunc():
num = 10
return num
print(num)
print(myfunc())
print(num)
Explanation: num = 1 — This
line assigns the value 1 to the global variable num.
def myfunc() — This line
defines a function named myfunc.
print(num) — This line prints
the value of the global variable num, which is 1.
print(myfunc()) — This line
calls the myfunc function. Inside myfunc function, num = 10 defines a local
variable num and assigns it the value of 10 which is then returned by the
function. It is important to note that the value of global variable num is
still 1 as num of myfunc is local to it and different from global variable num.
print(num) — This line prints
the value of the global variable num, which is still 1.
Question 6(iii).
What will be the output of following program?
Answer:
Output 1 10 10 |
def myfunc():
global num
num = 10
return num
print(num)
print(myfunc())
print(num)
Explanation: num = 1 — This
line assigns the value 1 to the global variable num.
def myfunc() — This line
defines a function named myfunc.
print(num) — This line prints
the value of the global variable num, which is 1.
print(myfunc()) — This line
calls the myfunc function. Inside the myfunc function, the value 10 is assigned
to the global variable num. Because of the global keyword used earlier, this
assignment modifies the value of the global variable num to 10. The function
then returns 10.
print(num) — This line prints
the value of the global variable num again, which is still 1.
Question 6(iv) What will be the output of following program?
Answer:
Output Hellothere! |
print("Hello", end='')
display()
print("there!")
Explanation: The function display
prints "Hello" without a newline due to the end='' parameter. When
called, it prints "Hello". Outside the function, "there!"
is printed on the same line due to the absence of a newline.
Q7. 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)
Answer
The code raises
an error when executed.
Explanation : In the provided
code, the global variables a and y are initialized to 10 and 5, respectively.
Inside the myfunc function, the line a = 2 suggests that a is a local variable
of myfunc. But the line before it, y = a is trying to assign the value of local
variable a to local variable y even before local variable a is defined.
Therefore, this code raises an UnboundLocalError.
Q8. What is
wrong with the following function definition?
def
addEm(x, y, z):
return x + y + z
print("the answer is", x + y + z)
Answer: In the
above function definition, the line print("the answer is", x + y + z)
is placed after the return statement. In python, once a return statement is
encountered, the function exits immediately, and any subsequent code in the
function is not executed. Therefore, the print statement will never be
executed.
Q9. Write a
function namely fun that takes no parameters and always returns None.
Answer
def
fun():
return
Explanation
def
fun():
return
r
= fun()
print(r)
The function
fun() returns None. When called, its return value is assigned to r, which holds
None. Then print(r) outputs None.
Q10. 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)
(i)
When the code above is executed, what prints out?
(ii)
What is variable output equal to after the code is executed?
Ans. (i) When
the code above is executed, it prints:
5 times 5 = 25
(ii) After the
code is executed, the variable output is equal to 25. This is because the
function multiply returns the result of multiplying 5 and 5, which is then
assigned to the variable output.
Q11. 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?
Ans. (i) When
the code above is executed, it will not print anything because the print
statement after the return statement won't execute. Therefore, the function
exits immediately after encountering the return statement.
(ii) After the
code is executed, the variable output is equal to 25. This is because the
function multiply returns the result of multiplying 5 and 5, which is then
assigned to the variable output.
Q12(a). Find
the errors in code given below:
def
minus(total, decrement)
output = total - decrement
print(output)
return (output)
Ans. The errors
in the code are:
def
minus(total, decrement) # Error 1
output = total - decrement
print(output)
return (output)
There should be
a colon at the end of the function definition line.
The corrected
code is given below:
def minus(total, decrement):
output = total - decrement
print(output)
return (output)
Q12(b). Find
the errors in code given below:
define check()
N =
input ('Enter N: ')
i =
3
answer = 1 + i ** 4 / N
Return answer
Ans. The errors
in the code are:
define check()
#Error 1
N = input ('Enter N: ') #Error 2
i = 3
answer = 1 + i ** 4 / N
Return answer #Error 3
The function
definition lacks a colon at the end.
The 'input'
function returns a string. To perform arithmetic operations with N, it needs to
be converted to a numeric type, such as an integer or a float.
The return
statement should be in lowercase.
The corrected
code is given below:
def check():
N =
int(input('Enter N:'))
i =
3
answer = 1 + i ** 4 / N
return answer
Q12(c). Find
the errors in code given below:
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. The errors
in the code are:
def alpha (n, string = 'xyz', k = 10) :
return beta(string)
return n #Error 1
def beta (string) #Error 2
return string == str(n)
print(alpha("Valentine's Day"):)
#Error 3
print(beta(string = 'true')) #Error 4
print(alpha(n = 5, "Good-bye"):)
#Error 5
The second
return statement in the alpha function (return n) is unreachable because the
first return statement return beta(string) exits the function.
The function
definition lacks colon at the end. The variable n in the beta function is not
defined. It's an argument to alpha, but it's not passed to beta explicitly. To
access n within beta, we need to either pass it as an argument or define it as
a global variable.
There should
not be colon at the end in the function call.
In the function
call beta(string = 'true'), there should be argument for parameter n.
In the function
call alpha(n = 5, "Good-bye"), the argument "Good-bye" lacks
a keyword. It should be string = "Good-bye".
The corrected
code is given below:
def
alpha(n, string='xyz', k=10):
return beta(string, n)
def
beta(string, n):
return string == str(n)
print(alpha("Valentine's
Day"))
print(beta(string='true',
n=10))
print(alpha(n=5,
string="Good-bye"))
Q13. Draw the
entire environment, including all user-defined variables at the time line 10 is
being executed.
1.
def sum(a, b, c, d):
2. result = 0
3. result = result + a + b + c + d
4. return result
5.
6.
def length():
7. return 4
8.
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))
Ans. The
environment when the line 10 is being executed is shown below:
Draw the entire
environment, including all user-defined variables at the time line 10 is being
executed. Python Computer Science Sumita Arora Solutions CBSE Class 12
Q14. Draw flow
of execution for the above program.
Ans. The flow
of execution for the above program is as follows:
1 → 6 → 9 → 12
→ 1 → 2 → 3 → 4 → 6 → 7 → 9 → 10 → 12
Line 1 is
executed and determined that it is a function header, so entire function-body
(i.e, lines 2, 3, 4) is ignored.Then line 6 is executed and determined that it
is a function header, so entire function-body (i.e, line 7) is ignored, Line 9
is executed and determined that it is a function header, so entire
function-body (i.e, line 10) is ignored. Then line 12 is executed and it has a
function calls, so control jumps to the function header (line 1) and then first
line of function-body, i.e, line 2, function returns after line 4 to function
call line (line 12) and then control jumps to line 6, it is a function header
and then first line of function-body, i.e., line 7, function returns after line
7 to function call line (line 12) and then control jumps to line 9, it is a
function header and then first line of function-body, i.e., line 10, function
returns after line 10 to function call line 12.
Q15. Find and
write the output of the following python code:
a = 10
def call():
global a
a =
15
b =
20
print(a)
call()
Answer: Output
: 15
Explanation
a = 10 — This line assigns
the value 10 to the global variable a.
def call() — This line
defines a function named call.
a = 15 — Inside the call
function, this line assigns the value 15 to the global variable a. As global
keyword is used earlier, this assignment modifies the value of the global
variable a.
b = 20 — Inside the call
function, this line assigns the value 20 to a local variable b.
print(a) — This line prints
the value of the global variable a, which is 15. This is because we've modified
the global variable a inside the call function.
Q16. 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. In the
code, variables a and b are in the same scope because they are defined within
the same function func1(). Similarly, variables c and d are in the same scope
because they are defined within the same function func2(). e being a global
variable is not in the same scope.
Q17. Write a
program with a function that takes an integer and prints the number that
follows after it. Call the function with these arguments:
Output The print_number following 4 is 5 The print_number following 6 is 7 The print_number following 8 is 9 The print_number following 3 is 4 The print_number following -2 is -1 The print_number following -5 is -4 |
Ans.
1. def print_number(number):
2. next_number = number + 1
3. print("The number following", number,
"is", next_number)
4. print_number(4)
5. print_number(6)
6. print_number(8)
7. print_number(2 + 1)
8. print_number(4 - 3 * 2)
9. print_number(- 3 - 2)
Explanation:
def print_number(number) —
This line defines a function named print_number that takes one argument number.
next_number = number + 1 —
Inside the print_number function, this line calculates the next number after
the input number by adding 1 to it and assigns the result to the variable
next_number.
print("The number
following", number, "is", next_number) — Inside the print_number
function, this line prints a message stating the number and its following
number.
Then the print_number
function is called multiple times with 4, 6, 8, 3 ,((4 - 3 * 2) = -2), ((-3-2)
= -5) as arguments.
Q18. Write a
program with non-void version of above function and then write flow of
execution for both the programs.
Ans. The
non-void version of above code is as shown below:
Output 5 7 9 4 -1 -4 |
2.
next_number = number + 1
3.
return next_number
4. print(print_number(4))
5. print(print_number(6))
6. print(print_number(8))
7. print(print_number(2 + 1))
8. print(print_number(4 - 3 * 2))
9. print(print_number(-3 - 2))
Explanation:
def print_number(number) —
This line defines a function named print_number that takes one argument number.
next_number = number + 1 —
Inside the print_number function, this line calculates the next number after
the input number by adding 1 to it and assigns the result to the variable
next_number.
return next_number — Inside
the print_number function, this line returns next_number.
Then the print_number function
is called multiple times with 4, 6, 8, 3 ,((4 - 3 * 2) = -2), ((-3-2) = -5) as
arguments.
The flow of execution for the
above program with non-void version is as follows:
1 → 4 → 1 → 2 → 3 → 4 → 5 → 1
→ 2 → 3 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 1 → 2 → 3 → 7 → 8 → 1 → 2 → 3 → 8 → 9 → 1
→ 2 → 3 → 9
Line 1 is executed and
determined that it is a function header, so entire function-body (i.e., line 2
and 3) is ignored. Then line 4 is executed and it has function call, so control
jumps to the function header (line 1) and then to first line of function-body,
i.e., line 2, function returns after line 3 to line containing function call
statement i.e., line 4. The next lines 5, 6, 7, 8, 9 have function calls so
they repeat the above steps.
The flow of execution for the
void version program is as follows:
1 → 4 → 1 → 2 → 3 → 4 → 5 → 1
→ 2 → 3 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 1 → 2 → 3 → 7 → 8 → 1 → 2 → 3 → 8 → 9 → 1
→ 2 → 3 → 9
Line 1 is executed and
determined that it is a function header, so entire function-body (i.e., line 2
and 3) is ignored. Then line 4 is executed and it has function call, so control
jumps to the function header (line 1) and then to first line of function-body,
i.e., line 2, function returns after line 3 to line containing function call
statement i.e., line 4. The next lines 5, 6, 7, 8, 9 have function calls so
they repeat the above steps.
Q19(i). What is
the output of following code fragments?
Output [1,
2, 3, [4]] [1, 2, 3, [4]] |
n.append([4])
return n
L = [1, 2, 3]
M = increment(L)
print(L, M)
Answer
Explanation: In the code, the
function increment appends [4] to list n, modifying it in place. When L = [1,
2, 3], calling increment(L) changes L to [1, 2, 3, [4]]. Variable M receives
the same modified list [1, 2, 3, [4]], representing L. Thus, printing L and M
results in [1, 2, 3, [4]], confirming they reference the same list. Therefore,
modifications made to list inside a function affect the original list passed to
the function.
Q19(ii). What
is the output of following code fragments?
Answer: Output [23, 35, 47, [49]] 23 35 47 [49] True |
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)
Explanation : The function
increment appends [49] to list n and returns its first four elements
individually. When L = [23, 35, 47], calling increment(L) modifies L to [23,
35, 47, [49]]. Variables m1, m2, m3, and m4 are assigned the same list [23, 35,
47, [49]], representing the original list L. Thus, printing L and m1, m2, m3,
m4 yields [23, 35, 47, [49]]. The expression L[3] == m4 evaluates to True,
indicating that the fourth element of L is the same as m4.
Q20. What will
be the output of the following Python code?
V = 25
def Fun(Ch):
V =
50
print(V, end = Ch)
V
*= 2
print(V, end = Ch)
print(V, end = "*")
Fun("!")
print(V)
25*50!100!25
50*100!100!100
25*50!100!100
Error
Answer
25*50!100!25
Explanation
V = 25 — initializes global
variable V to 25.
print(V, end = "*")
— Prints the global variable V (25) followed by an asterisk without a newline.
Fun("!") — Calls
the function Fun with the argument "!".
Inside function Fun, V = 50
initializes a local variable V within the function with the value 50. This
variable is different from the global variable V that has the value 25.
print(V, end = Ch) — Prints
the local variable V (50) followed by the character passed as an argument to
the function, which is "!".
V *= 2 — Multiplies the local
variable V (50) by 2, making it 100.
print(V, end = Ch) — Prints
the updated local variable V (100) followed by the character "!".
The function Fun returns and
the line print(V) is executed. It prints the global variable V without any
newline character. The global variable V remains unchanged (25).
#######################################################################
1. What is the default return value for a
function that does not return any 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) rerun value
3. Which of the following keywords marks
the beginning of the function block?
(a) Func (b) define (d) def
(d) function
4. What is the name given to that area of
memory, where the system stores the parameters and local variable of a function
call?
(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?
7. Which of the following statements is
not true for parameter passing to function?
8. Which of the following function calls
can be used to invoke the below function definition?
9. Which of the following function calls
will cause Error while invoking the below function definition?
10. 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
11. 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
12. Carefully observe the code and give the
answer.
13. What is the result of this code?
14. What is the order of resolving scope of a
name in a Python program?
15. Which of the given argument type can be
skipped form a function call?
Fill in the
Blanks
1. A________is
a subprogram that acts on data and often returns a value.
2. Python names
the top level segment (main program) as _________.
3. In Python,
program execution begins with first statement of ______segment.
4. The values
being passed through a function-call statement are called_____.
5. The values
received in the function definition/header are called________.
6. A parameter
having default value in the function header is known as a_______.
tion ?
7. A ________
argument can be skipped in the function call statement.
8.__________
arguments are the named arguments with assigned values being passed in the
function call statement.
9. A void
function also returns a _______value to its caller.
10. By default,
Python names the segment with top-level statements (main program) as_________.
11. The
________refers to the order in which statements are executed during a program
run.
12. The default
value for a parameter is defined in function_________.
True/False
Questions
1. Non-default arguments can be placed
before or after a default argument in a function definition.
2. A parameter having default value in the
function header is known as a default parameter.
3. The first line of function definition
that begins with keyword def and ends with a colon (:), is also known as
function header.
4. Variables that are listed within the parentheses
of a function header are called function variables.
5. In Python, the program execution
begins with first statement of _main_ segment.
6. Default parameters cannot be skipped in
function call.
7. The default values for parameters are
considered only if no value is provided for that parameter in the function call statement.
8. A python function may return multiple
values.
9. A void function also returns a value
i.e., None to it called.
10. Variable defined inside functions can
have global scope.
11. A local variable having the same name as
that of a global variable hides the global variable in its function.
COMPUTER
SCIENCE WITH Pre
Assignment
Type A Short
Answer Questions/Conceptual Questions
1. A program
having multiple functions is considered better designed than without any
functions. Why?
2. What all
information does a function header give you about the function ? & What do
you understand by flow of execution?
4. What are
arguments? What are parameters? How are these two terms different yet related t
10 default arguments, (i) keyword arguments ? & What is the utility of
Explain with a
code example the usage of default arguments and keyword argument 7. Describe
the different styles of functions in Python using appropriate examples
& Differentiate
between fruitful functions and non-fruitful functions
Can a function
return multiple values? How?
18 What is
scope 7 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 recommended?
13. Write the
term suitable for following descriptions:
(a) A name
inside the parentheses of a function header that can receive a value. (b) An
argument passed to a specific parameter using the parameter name.
(c) A value
passed to a function parameter.
(4) A value
assigned to a parameter name in the function header.
(e) A value
assigned to a parameter name in the function call.
A name defined
outside all function definitions
(g) A variable
created inside a function body
14. What do you
understand by local and global scope of variables? How can you access a global
variable the function, if function has a variable with same name.
Type B:
Application Based Questions
(CBSE Sample
Paper 20
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;
Chapter 3
2. Find
sum( 10, 20);
print("Total",
total)
(b)
def Tot
(Number)
#Method to find
Total
Sum-8
for C in Range
(1, Number + 1):
Sum + C
RETURN Sum
print (Tot[3])
#Function Calls
print (Tot[6])
CBSE D 2015
Dfgdgdgdgdgd
Type C:
Programming Practice/Knowledge based Questions
1. Write a function that takes
amount-in-dollars and dollar-to-rupee conversion price; it then returns the
amount converted to rupees. Create the function in both void and non-void
forms.
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:
(a) length of box;
(b) width of box;
(c) height of box.
Test it by
writing complete program to invoke it.
3. Write a program to have following
functions:
(i) 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 i.e., The default
value of n is 2.
7. Write a function that takes a number n
and then returns a randomly generated number having exactly n digits (not
starting with zero) e.g., if n is 2 then function can randomly return a number
10-99 but 07, 02 etc. are not valid two digit numbers.
8. Write a function that takes two numbers
and returns the number that has minimum one's digit. [For example, if numbers
passed are 491 and 278, then the function will return 491 because it has got
minimum one's digit out of two given numbers (491's 1 is < 278's 8)].
9. Write a program that generates a series
using a function which takes first and last values of the series and then
generates four terms that are equidistant e.g., if two numbers passed are 1 and
7 then function returns 13 5 7.
Question3
Explanation [back to question]
Line 1 is
executed and determined that it is a function header, so entire function-body
(i.e., lines 2 and 3) is ignored. Line 5 is executed and determined that it is
a function header, so entire function-body (i.e., lines 6 and 7) is ignored.
Lines 9 and 10 are executed, line 10 has a function call, so control jumps to
function header (line 5) and then to first line of function-body, i.e., line 6,
it has a function call , so control jumps to function header (line 1) and then
to first line of function-body, i.e, line 2. Function returns after line 3 to
line 6 and then returns after line 7 to line containing function call statement
i.e, line 10 and then to line 11.
Comments
Post a Comment