GR12 CS CH 3 FUNCTIONSujv
GR12 CS CH 3 FUNCTIONSujv
1.A program having multiple functions is considered better designed than a program without any functions. Why
?
A program having multiple functions is considered better designed than a program without any functions because
1. It makes program handling easier as only a small part of the program is dealt with at a time, thereby
avoiding ambiguity.
2. It reduces program size.
3. Functions make a program more readable and understandable to a programmer thereby making program
management much easier.
2.What all information does a function header give you about the function ?
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.
4.What are arguments ? What are parameters ? How are these two terms different yet related ? Give example.
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.
6.Explain with a code example the usage of default arguments and keyword arguments.
Default arguments — Default arguments are used to provide a default value to a function parameter if no
argument is provided during the function call.
For example :
def greet(name, message="Hello"):
print(message, name)
greet("Alice")
greet("Bob", "Hi there")
Output
Hello Alice
Hi there Bob
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.
Keyword arguments — Keyword arguments allow us to specify arguments by their parameter names during a
function call, irrespective of their position.
def person(name, age, city):
print(name, "is", age, "years old and lives in", city)
10.
What is scope ? What is the scope resolving rule of Python ?
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).
12. When is global statement used ? Why is its use not recommended ?
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.
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.
Question 1(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)
Answer
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
Explanation
1. There is an indentation error in second line.
2. The return statement should be indented inside function and it should not end with semicolon.
3. Function call should not end with semicolon.
Question 1(b)
What are the errors in following codes ? Correct the code and predict output :
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])
Answer
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
Explanation
1. There should be a colon (:) at the end of the function definition line to indicate the start of the function
block.
2. Python's built-in function for generating sequences is range(), not Range().
3. Python keywords like return should be in lowercase.
4. When calling a function in python, the arguments passed to the function should be enclosed inside
parentheses () not square brackets [].
Question 2
Find and write the output of the following python 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)
Answer
Output
300 @ 200
300 @ 100
120 @ 100
300 @ 120
Explanation
1. Function Call is defined with two parameters P and Q with default values 40 and 20 respectively.
2. Inside the function Call, P is reassigned to the sum of its original value P and the value of Q.
3. Q is reassigned to the difference between the new value of P and the original value of Q.
4. Prints the current values of P and Q separated by @.
5. The function returns the final value of P.
6. Two variables R and S are initialized with values 200 and 100 respectively.
7. The function Call is called with arguments R and S, which are 200 and 100 respectively. Inside the
function, P becomes 200 + 100 = 300 and Q becomes 300 - 100 = 200. So, 300 and 200 are printed. The
function returns 300, which is then assigned to R. Therefore, R becomes 300.
8. S = Call(S) — The function Call is called with only one argument S, which is 100. Since the default
value of Q is 20, P becomes 100 + 20 = 120, and Q becomes 120 - 20 = 100. So, 120 and 100 are printed.
The function returns 120, which is then assigned to S. Therefore, S becomes 120.
Question 3
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)
Answer
The flow of execution for the above program is as follows :
1 → 5 → 9 → 10 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11
Explanation
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.
Question 4
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.
Question 5
What will the following function print when called ?
def addEm(x, y, z):
return x + y + z
print(x + y + z)
Answer
The function addEm prints nothing when called.
Explanation
The function addEm(x, y, z) takes three parameters x, y, and z.
1. It returns the sum of x, y, and z.
2. 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.
Question 6(i) - What will be the output of following program ?
num = 1
def myfunc():
return num
print(num)
print(myfunc())
print(num)
Answer
Output
1
1
1
Explanation
The code initializes a global variable num with 1. myfunc just returns this global variable. Hence, all the
three print statements print 1.
1. num = 1 — This line assigns the value 1 to the global variable num.
2. def myfunc() — This line defines a function named myfunc.
3. print(num) — This line prints the value of the global variable num, which is 1.
4. 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.
5. print(num) — This line prints the value of the global variable num again, which is still 1.
Question 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)
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.
Question 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)
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.
Question 9- 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.
Question 10 - 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 ?
Answer
(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.
Question 11 - 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 ?
Answer
(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.
Question 12(c)
Find the errors in code given below :
def alpha (n, string = 'xyz', k = 10) :
return beta(string)
return n
print(alpha("Valentine's Day"):)
print(beta(string = 'true'))
print(alpha(n = 5, "Good-bye"):)
Answer
The errors in the code are:
def alpha (n, string = 'xyz', k = 10) :
return beta(string)
return n #Error 1
print(alpha("Valentine's Day"))
print(beta(string='true', n=10))
print(alpha(n=5, string="Good-bye"))
Question 13
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))
Answer
The environment when the line 10 is being executed is shown below :
Question 14
Draw flow of execution for the above program.
Answer
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.
15. 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
1. a = 10 — This line assigns the value 10 to the global variable a.
2. def call() — This line defines a function named call.
3. 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.
4. b = 20 — Inside the call function, this line assigns the value 20 to a local variable b.
5. 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.
16.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
Answer
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.
17.Write a program with a function that takes an integer and prints the number that follows after it. Call the
function with these arguments :
4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2
Answer
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)
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
Explanation
1. def print_number(number) — This line defines a function named print_number that takes one
argument number.
2. 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.
3. 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.
4. Then the print_number function is called multiple times with 4, 6, 8, 3 ,((4 - 3 * 2) = -2), ((-3-2) = -5) as
arguments.
Question 18
Write a program with non-void version of above function and then write flow of execution for both the programs.
Answer
The non-void version of above code is as shown below :
1. def print_number(number):
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))
Output
5
7
9
4
-1
-4
Explanation
1. def print_number(number) — This line defines a function named print_number that takes one
argument number.
2. 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.
3. return next_number — Inside the print_number function, this line returns next_number.
4. 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.
Question 19(i) - 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)
Answer
Output
[1, 2, 3, [4]] [1, 2, 3, [4]]
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.
Question 19(ii) - What is the output of following code fragments ?
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)
Answer
Output
[23, 35, 47, [49]]
23 35 47 [49]
True
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.
Question 20
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)
1. 25*50!100!25
2. 50*100!100!100
3. 25*50!100!100
4. Error
Answer
25*50!100!25
Explanation
default_volume = calculate_volume()
print("Volume of the box with default values:", default_volume)
v = calculate_volume(10, 7, 15)
print("Volume of the box with default values:", v)
a = calculate_volume(length = 23, height = 6)
print("Volume of the box with default values:", a)
b = calculate_volume(width = 19)
print("Volume of the box with default values:", b)
Output
Volume of the box with default values: 30
Volume of the box with default values: 1050
Volume of the box with default values: 414
Volume of the box with default values: 190
Question 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.
Solution
# Function to calculate cube of a number
def calculate_cube(number = 2):
cube = number ** 3
print("Cube of", number, "is", cube)
calculate_cube(3)
calculate_cube()
char1 = 'a'
char2 = 'b'
print("Characters are equal:", check_equal_chars(char1, char1))
print("Characters are equal:", check_equal_chars(char1, char2))
Output
Cube of 3 is 27
Cube of 2 is 8
Characters are equal: True
Characters are equal: False
Question 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.
Solution
import random
for i in range(3):
random_num = generate_random_number(num1, num2)
print("Random number between", num1, "and", num2, ":", random_num)
Output
Enter the first number: 2
Enter the second number: 78
Random number between 2 and 78 : 77
Random number between 2 and 78 : 43
Random number between 2 and 78 : 52
Question 5
Write a function that receives two string arguments and checks whether they are same-length strings (returns
True in this case otherwise False).
Solution
def same_length_strings(str1, str2):
return len(str1) == len(str2)
s1 = "hello"
s2 = "world"
s3 = "python"
print(same_length_strings(s1, s2))
print(same_length_strings(s1, s3))
Output
True
False
Question 6
Write a function namely nthRoot( ) that receives two parameters x and n and returns nth root of x i.e., x^(1/n).
The default value of n is 2.
Solution
def nthRoot(x, n = 2):
return x ** (1/n)
result = nthRoot(x, n)
print("The", n, "th root of", x, "is:", result)
default_result = nthRoot(x)
print("The square root of", x, "is:", default_result)
Output
Enter the value of x:36
Enter the value of n:6
The 6 th root of 36 is: 1.8171205928321397
The square root of 36 is: 6.0
Question 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.
Solution
import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)
Output
Enter the value of n:2
Random number: 10
Question 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)].
Solution
def min_ones_digit(num1, num2):
ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
if ones_digit_num1 < ones_digit_num2:
return num1
else:
return num2
Solution
def generate_series(first, last):
step = (last - first) // 3
series = [first, first + step, first + 2 * step, last]
return series
Output
Enter first value:1
Enter last value:7
Generated Series: [1, 3, 5, 7]