In this article, I am going to discuss Comprehensive solutions Preeti Arora Chapter 2 Functions unsolved questions computer science class 12. So let us begin!
Topics Covered
Chapter 2 Functions Preeti Arora Class 12 Unsolved Questions Computer science || Solution Chapter 2 Functions unsolved questions Computer Science Class 12
[1] A program having multiple functions is considered better designed than a program without any function. Why?
Ans.: A program having multiple functions is cosidered better designed that a program without any function because of:
i) Reusibility of code
ii) Reduces the repetitive code lines into a program
iii) Easy to manage and understand
iv) Divide the program in small functions and tasks
v) Code becomes very compact
vi) A program becomes more readable
vii) Any updation can be done easily
[2] Write a function called calculate_area() that takes base and height as input arguments and returns the area of a triangle as an output. The formula used is:
Triangle Area = 1/2*base*height
Ans.:
def calculate_area(base,height):
return 1/2*base*height
b=int(input("Enter base:'))
h=int(input("Enter Height"))
area=calculate_area(b,h)
print("The area of triangle is:",area)
[3] Modify the above function to take a third parameter called shape type. The shape type should be either triangle or rectangle. Based on the shape, it should calculate the area.
Formula used: Rectangle Area = length*width
Ans.:
def calculate_area(p1,p2,shape):
if shape=='triangle':
return 1/2*p1*p2
elif shape=='rectangle':
return length*width
else:
priint("Invalid Shape, Shape must triangle or rectangle")
s=input("Enter shape:")
a=int(input("Enter parameter1:"))
b=int(input("Enter parameter2:"))
area=calculate_area(a,b,s)
print("The area of ",s, " is:", area)
[4] Write a function called print_pattern that takes an integer number as an argument and prints the following pattern.
If the input number is 3.
*
* *
* * *
If input is 4, then it should print:
*
* *
* * *
* * * *
Ans.:
def print_pattern(n):
for i in range(1,n+1):
for j in range(1,i+1):
print('*',end='')
print("\n")
x=int(input("Enter no. of lines:"))
print_pattern(x)
[5] What is the utility of: –
(I) default arguments (II) Keyword arguments
Ans.:
(I) Default Arguments: Default arugments are thos arguments which are assigned the values in the funtion. The default argument must be initialized the value in function definition and takes a default value while calling. In the calling function the value is not provided by the calling statement because it gets the detfauts from function definition. The default arguments must be assigned from right to left in the function header.
(II) Keyword Argument: Keyword arguments are the named arguments with assigned values being passed in function call statement, the user can combine any type of argument.
[6] Describe the different types of functions in Python using appropriate examples.
Ans.: Python supports three types of functions:
1) Built-in functions
2) Functions defined in the module
3) User-defined functions
1) Build-in functions: The built-in functions are those functions which are already defined in the python standard library. For example: len(), sum(), input(), print() etc.
Ex.:
a=’Hello’
print(len(a))
Output: 5
2) Functions defined in the module: Python provides many modules to perform specific tasks in the program. User can access any function from the after importing that module in the program. The functions defined in the module can be accessed by this way:
Ex.:
import math
n=5
print(math.pow(n,2))
Output:25
Modules can be also imported using this statement:
from
Ex.: from math import pow
3) User defined functions: These functions are created by the user. It starts with def keyword followed by functions name and required parameters.
Ex.:
def add(n1,n2):
return n1+n2
print(add(5,6))
[7] What is the scope? What is the scope resolving rule of Python?
Ans.: The scope refers to a location or a part of a variable in python program where it is accessible. A python program has various functions and parts. All parts contains many variables. These variables have their access according to their declaration. If it is declared inside the function that variable is accesible to the same function only. Outside the function that variable is not accessible. Similarly a Global variable can be accessed in any function.
The scope resolving rules of python are known as LEGB rule.
L – L refers to local scope it means that python checks the variable inside same function (local environment)
E – E refers to Environment scope it means that python checks the variable scope in its execution environment
G – G refers to global scope it means that python checks the variable in the global scope i.e. a variable is declared in top level statement and accessed throught the program
B – B refers to built-in scope that means the variable is checked inside buit-in environment
[8] What is the difference between local and global variables?
Ans.:
The local variable is accessible only inside the function where it is declared. It does not require any special keyword.
The global variable is accessible throughout the program. First it is decalred in top level statements and required global keyword.
[9] Write the term suitable for following description:
(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.
(d) A value assigned to a parameter name in the function header.
(e) A value assigned to a parameter name in the function call.
(f) A name defined outside all function definitions.
(g) A variable created inside a function body.
Ans.:
(a) Parameters
(b) Keyword Argument
(c) Argument
(d) Default argument
(e) Keyword Argument
(f) Global Variable
(g) Local Variable
[10] Consider the following code and write the flow of execution for this. Line numbers have been given for our reference.
def power (b, p): #1
y = b ** p #2
return y #3
#4
def calcSquare(x): #5
a = power (x, 2) #6
return a #7
#8
n = 5 #9
result = calcSquare(n) #10
print (result) #11
Ans.:
Ans.
1->4->5->8->9->10->6->2->3->7->11
[11] What will the following function return?
def addEm(x, y, z):
print (x + y + z)
Ans.:
None
[12] What will be the output displayed when addEM() is called/executed?
def addEm(x, y, z):
return x + y + z
print (x+ y + z)
Ans.:
It does not print anything as function contains only return statement and print() function is given after return.
[13] What will be the output of the following programs?
(i)
num = 1
def myFunc ():
return num
print(num)
print(myFunc())
print(num)
(ii)
num = 1
def myfunc():
num = 10
return num
print (num)
print(myfunc())
print(num)
(iii)
num = 1
def myfunc ():
global num
num = 10
return num
print (num)
print(myfunc())
print(num)
(iv)
def display():
print(“Hello”, end = ‘ ‘)
display()
print(“there!”)
Ans.
(i)
1
1
1
(ii)
1
10
1
(iii)
1
10
10
(iv)
Hello there!
[14] Predict the output of the following code:
a = 10
y = 5
def myfunc(a):
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.:
y = 5 a = 10
y = 10 a = 2
a+y = 12
12
y = 5 a = 10
[15] 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 the above functions print() should not be used after return as in the function body the return statement returns the final value. Here it will not print the addition of x,y and z.
[16] Find the errors in the code given below:
(a)
def minus (total, decrement)
output = total – decrement
print(output)
return (output)
(b)
define check()
N = input (“Enter N: “)
i = 3
answer = 1 + i ** 4 / N
Return answer
(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.:
a) The correct code:
def minus(total,decrement):
&nbps;&nbps;&nbps;&nbps;output=total-decrement
&nbps;&nbps;&nbps;&nbps;print(output)
Explanation: In line 1 colon is missing in the function header. The return and print statement only one statement is enough. So i have removed retrun statement.
b) The correct code:
def check():
&nbps;&nbps;&nbps;&nbps; N=int(input(“Enter N:”))
&nbps;&nbps;&nbps;&nbps; i=3
&nbps;&nbps;&nbps;&nbps; answer=1 + i ** 4 /N
&nbps;&nbps;&nbps;&nbps; return answer
Explanation:
i) Line 1: Define should be replaced with def and colon is missing.
ii) Line 2: int() is missing as input function accepts only string
iii) Line 4: R must be in lower case
c) The correct code:
def alpha (n, string =’xyz’, k = 10) :
&nbps;&nbps;&nbps;&nbps;return beta(string)
&nbps;&nbps;&nbps;&nbps;return n
def beta (string,n=1):
&nbps;&nbps;&nbps;&nbps; return string == str(n)
print(alpha(“Valentine’s Day”))
print(beta(‘true’))
print(alpha(5,’Good Bye’,2))
Explanation:
1. Function beta requires 1 parameter with default argument as comparison is given in the return statement with n and colon is missing.
2. In last statement the function is not called properly with proper arguments.
[17] Define flow of execution. What does it do with functions?
Ans.:
i) A python program with function ony executes when the function is called.
ii) To call a function write function name along with the parameters and values if required.
iii) When the function is called an execution frame is created and return a value or execute the last statement written in the function.
iv) Python follows top to bottom approach while calling the function
v) If any comments written in the function will be ignored by the python interpreter
v) When python finds a function header it just executes the first line and then skip the whole function body statements. These statement will be executed when function is called.
[18] 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.
Ans.:
Void Function:
def DollarToRupee(amt):
r=amt*79.20
print("Dollar to rupees:",r)
Non void function:
def DollarToRupee(amt):
return amt*79.20
[19] 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.
Ans.:
def volume(length,width,height):
return length * width * height
volume(3,4,5)
[20] Write a program to display first four multiples of a number using recursion.
[21] What do you understand by recursion? State the advantages and disadvantages of using recursion.
[22] Write a recursive function to add the first ‘n’ terms of the series:
1+1/2-1/3+1/4-1/5……
Note: Recursion is deleted from the syllabys of 2022-23.
[23] Write a program to find the greatest common divisor between two numbers.
Ans.
def compute_gcd(n1, n2):
if n1 > n2:
smaller = n2
else:
smaller = n1
for i in range(1, smaller+1):
if((n1 % i == 0) and (n2 % i == 0)):
gcd = i
return gcd
num1 = int(input("Enter number1:"))
num2 = int(input("Enter number2:"))
print("The H.C.F. is", compute_gcd(num1, num2))
[24] Write a Python function to multiply all the numbers in a list.
Sample List: (8, 2, 3, -1, 7)
Expected Output: -336
Ans.:
li=[]
n=int(input("Enter no. of elements of the list:"))
for i in range(n):
v=int(input("Enter element to add into the list:"))
li.append(v)
def multiply_li(l):
m=1
for i in l:
m*=i
return m
print("Multiplication of list element is:",multiply_li(li))
[25] Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number whose factorial is to be calculated as the argument.
Ans.:
def facto(n):
f=1
for i in range(1,n+1):
f*=i
return f
n=int(input("Enter no to find factorial:"))
print("The factorial is:",facto(n))
[26] Write a Python function that takes a number as a parameter and checks whether the number is prime or not.
Ans.:
num = int(input("Enter a number: "))
def chkPrime(n):
flag = False
if n > 1:
for i in range(2, n):
if (n % i) == 0:
flag = True
break
if flag==True:
print(n, "is not a prime number")
else:
print(n, "is a prime number")
print(chkPrime(num))
[27] Write a Python function that checks whether a passed string is a palindrome or not.
Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Ans.:
def check_palin (s):
for i in range (0, int (len (s)/2)):
if s [i] != s [len (s) -i-1]:
return False
return True
txt = input ("Enter a string.")
ans = check_palin (txt)
if (ans):
print ("Yes, it is a palindrome.")
else:
print ("No, it is not a palindrome.")
[28] Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.
Sample Items: green-red-yellow-black-white
Expected Result: black-green-red-white-yellow
def word (w) :
for i in range (len(w) + 1) :
for j in range (len(w) - 1) :
if w[j][0] > w[j+1][0] :
w[j], w[j+1] = w[j+1], w[j]
string = ("-").join(w)
print("Sequence After sorting :- ", string)
txt = input ("Enter hyphen-separated sequence of words :- ")
a = txt.split("-")
word(a)
Note: Question 29 to 36 are based on recusrive function which is not in syllabus 2022-23.
[37] Predict the output of following codes.
(a)
def code (n):
if n== 0:
print('Finally ')
else:
print(n)
code(3)
code(15)
(b)
def code (n):
if n== 0:
print('Finally ')
else:
print(n)
code(2-2)
code(15)
(c)
def code (n):
if n== 0:
print('Finally')
else:
print(n)
code(10)
(d)
def code (n):
if n== 0:
print('Finally')
else:
print(n)
print(n - 3)
code(10)
Ans.:
(a)
3
15
(b)
Finally
15
(c)
10
(d)
10
7
Note: Question numbers 38 to 42 are based on recursion which is not in syllabus 2022-23.
[43] Write a method in Python to find and display the prime numbers to N. The value N should be passed as an argument to the method.
Ans.:
def chk_prime(n):
count = 0
for i in range(2, n + 1) :
count = 0
for j in range(2,i) :
if i % j == 0 :
count = 1
if count == 0 :
print(i,end=' ')
n=int(input("Enter n:"))
chk_prime(n)
[44] Write a definition of a method EvenSum(NUMBERS) to add those values in the tuple of NUMBERS which are even.
Ans.:
def EVENSUM(number):
s=0
for i in number:
if i%2==0:
s+=i
return s
t=eval(input("Enter values for a tuple"))
print("The sum of even numbers from tuple is:",EVENSUM(t))
[45] Write a definition of a method COUNTNOW(PLACES) to find and display those place names in which there are more than 5 characters after sorting the names of places in a dictionary. For example,
If the dictionary PLACES contains:
{1:’DELHI’,2:’LONDON’,3:’PARIS’,4:’NEW YORK’,5:’DUBAI’}
The following output should be displayed:
LONDON
NEW YORK
Ans.:
def COUNTNOW(places):
l=sorted(places.values())
for i in l:
if len(i)>5:
print(i)
d={}
while True:
n=int(input("Enter number to insert as key:"))
c=input("Enter city to insert as value:")
d[n]=c
ch=input("Press x to stop:")
if ch.lower()=='x':
break
COUNTNOW(d)
[46] Write a program using user defined function to calculate and display average of all the elements in a user defined tuple containing numbers.
Ans.:
def average(number):
s=0
for i in number:
s+=i
return s/len(number)
t=eval(input("Enter values for a tuple"))
print("The average of tuple elements is:",average(t))
[47] Name the built-in mathematical function/method:
(a) Used to return an absolute value of a number
(b) Used to return the values of x^y, where x and y are numeric expression
(c) Used to return a positive value of the expression in float
Ans.:
(a) math.abs()
(b) math.pow()
(c) math.fabs()
[48] Name the built-in String functions:
(a) Used to remove the space(s) from the left of the string
(b) Used to check if the string is uppercase or not
(c) Used to check if the string contains only whitespace characters or not
Ans.:
(a) lstrip()
(b) isupper()
(c) isspace(0
[49] Write a function LeftShift(lst,x) in Python which accept numbers in a list(lst) and all the elements of the list should be shifted to left according to the value of x:
Sample input data of the list lst = [20,40,60,30,10,50,90,80,45,29] where x=3
Output lst=[30,10,50,90,80,45,29,20,40,60]
Ans.:
def Lshift(li,n):
print("List pre shift:",li)
print("List post shift:",li[n:]+li[:n])
l=[]
n=int(input("Enter number to be shift:"))
while True:
val=int(input("Enter the value to add into list:"))
l.append(val)
ch=input("Press x to stop:")
if ch.lower()=='x':
break
Lshift(l,n)
Follow this link to read the solutions of Preeti Arora’s textbook computer science class 12 chapter 1 python basics review.
Preeti Arora Solutions Class 12 Computer Science Chapter 1 Review of Python Basics
Thank you for reading this article Chapter 2 Functions unsolved questions Computer Science Class 12. I hope it will help you to understand chapter 2 functions well.