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!
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?
[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
[6] Describe the different types of functions in Python using appropriate examples.
[7] What is the scope? What is the scope resolving rule of Python?
[8] What is the difference between local and global variables?
[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.
[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.:
[11] What will the following function return?
def addEm(x, y, z):
print (x + y + z)
[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)
[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!”)
[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)
[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)
[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”) 🙂
[17] Define flow of execution. What does it do with functions?
[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)
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.
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.