12th Standard CBSE Computer Science Functions Important Questions
By QB365 on 24 Apr, 2021
12th Standard CBSE Computer Science Functions Important Questions
QB365-Question Bank Software
Functions Important Questions
12th Standard CBSE
-
Reg.No. :
Computer Science
-
What will be the output of the following code?
print (type(type(int)))(a)type "int'
(b)< class 'type' > (c)Error
(d)< class "int' >
-
What will be the output of the following code?
L = ['a','b','c','d']
print (" ".join(L))(a)Error
(b)a b c d
(c)['a':b':c':d']
(d)None
-
What is called when a function is defined inside a class?
(a)Module
(b)Class
(c)Another function
(d)Method
-
Which of the following is the use of idf) function in python?
(a)Id() returns the identity of the object
(b)Every object doesn't have a unique ID
(c)All of the mentioned
(d)None of the mentioned
-
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list after list1.pop(1)?
(a)[3,4, 5, 20, 5, 25, 1, 3]
(b)[1, 3, 3, 4, 5, 5, 20, 25]
(c)[3,5, 20, 5, 25, 1, 3]
(d)[1,3,4,5,20,5,25]
-
Find and write the output of the following Python code:
def fun(s):
k=len(s) .
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('schooI2@com')(a) -
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.
(a) -
What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values that can be assigned to variable
PICKER. import random
PICKER = random.randint (0, 3)
COLOR = ["BLUE","PINK", "GREEN", "RED"]
for I in COLOR:
for J in range (1, PICKER) :
print (I, end = " ")
print ()(i) (ii) (iii) (iv) BLUE BLUE PINK BLUEBLUE PINK BLUEPINK PINKGREEN PINKPINK GREEN BLUEPINKGREEN GREENRED GREENGREEN RED BLUEPINKGREENRED REDRED (a) -
How can we import a module in Python?
(a) -
What are the differences between parameters and arguments?
(a) -
What are default arguments?
(a) -
What are keyword arguments?
(a) -
What are the advantages of keyword arguments?
(a) -
Write a generator function generatesq ( ) that displays the square roots of numbers from 100 to n where n is passed as an argument.
(a) -
What are the advantages of dividing a program into modules.
(a) -
Differentiate between Built-in functions and user defined functions.
(a) -
Differentiate between Built-in functions and functions defined in modules.
(a) -
Write a program that reads a number, then converts it into octal, hexadecimal, ASCII and Unicode string using built in functions of Python.
(a) -
Write the corresponding Python expression for the following mathematical expressions:
i) 2-ye2y +4y ii) Iex- x2 - xI(a) -
Write a Python program using functions to calculate area of a triangle after obtaining its three sides.
(a) -
How are following two statements different?
import math
from math import *(a) -
What will be the output of the following code
sinppet and why?
# module calculate.py
''''''This module will be imported"""
defsum 0:
"""Prints sum of 10 and 5"''''
b=5
a=10
print ("sum=",a+b)
return
def diff():
"""prints difference of 20 and 5"""
a=30
b=5
print ("Difference=", a-b)
return
print ("This will print something")
greet= "Hello!"
#Fun.py import calculate print calculate.gra(a) -
What is an execution frame?
(a) -
What is the difference between passing mutable type arguments and immutable type arguments to the function?
(a) -
What are Positional arguments?
(a) -
Is indentation required in Python?
(a) -
What is a default parameter? How is it specified?
(a) -
From the function calls given below for a function defined as def fun(p,t,r=7, c=8): determine which is valid and which one is invalid. Give reasons.
(i) fun(p=5, t=2)
(ii) fun(c=2, r=7)
(iii) fun (80,p=7,r=2)(a) -
What is name resolution rule? Explain it.
(a) -
What will be the output of the following program.?
1 def increase (x): (b) a=l
2 a= a+x def ft):
3 return a=10
4 print(a)
5 a=20
6 b=5
7 increase (b)
8 print(a)(a) -
Spot the errors and rewrite the corrected codes.
total=0;
def sum(arg1, arg2) :
total = arg1 + arg2
print("Total:", total)
return total
sum (10,20)
print("Total:" total)(a) -
What will following function print when called?
def addEm (x,y,z):
return x+y+z
print(x+y+z)(a) -
Predict the output of the following codes.
(a) num=l (Each part carries 2 marks)
def myfunct):
returnnum
print (num)
print (myfunc ())
print (num)(a) -
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(a) -
Write 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.
(a) -
Write a function that receives two string arguments and checks whether they are same-length strings (returns True in this case otherwise False)
(a) -
Write a function namely nthRoot() that receives two parameter x and n and return nth root of x ie. x1/n The default value of n is 2
(a) -
Write a function that takes two numbers and returns the number that has minimum one's digit.
(a) -
Write a void function that receives a 4 digit number and calculates the sum of squares of first two digits of the number and last two digits of the number egoif 1233 is passed as argument then function should calculate (12)2+(33)2
(a) -
Write a function to swap two numbers.
(a) -
What are the rules to define a' function in Python?
(a) -
What does the len() function do?
(a) -
How can you make a module 'helloworld' out of these two functions?
def hello():
print ('Hello,',)
def world():
print ('World!')(a) -
Define pow(x, y) function in Python.
(a) -
What is a Python module? What is its significance?
(a) -
"Python has certain functions that you can readily use without having to write any special code." What type of functions are these ?
(a) -
What is the utility of built-in function help () ?
(a) -
What is the utility of Python standard library's math module and random module?
(a) -
Explain Scope of Variables.
(a) -
Find the error
def minus (total, decrement)
output = total - decrement
return output(a) -
What would be the output produced by the following code:
import math
import random
print (math. ceil (random.random( )))(a) -
Find the error(s) in the following code and correct them:
1. def describe intelligent life form ():
2. height = input ("Enter the height")
3. raw_input ("Is it correct?")
4. weight = input ("Enter the weight")
5. favourite-game = input ("Enter favorite game")
6. print ("your height", height, 'and weight', weight)
7. print ("and your favourite game is", favouritism, '.')(a) -
Write a function that:
(i) Asks the user to input a diameter of circle in inches.
(ii) Sets a variable called radius to one half of that number.
(iii)Calculate the area of circle.
(iv) Print the area of circle with appropriate unit.
(v) Return this same amount as the output of the function(a) -
What would be the output of the following ?
Explain.
def f1()}:
n = 44
def f2 ():
n= 77
print ("value of n", n ())
print ("value of n",n)(a) -
What do you mean by globals() and locals() functions
(a) -
What are docstrings ?How are they useful?
(a) -
Explain global vs. local variables.
(a) -
Explain anonymous functions.
(a) -
Identify the following function definitions as void or non-void function.
(i) def fun():
print("Hello!")
(ii) def fun():
print("Hello!")
return(1)
(iii) def fun():
print("Hello!")
retum(1)
(iv) def fun():
return(2)
print("Hello")(a) -
How are docstring different from comments?
(a) -
Give the output of the following code:
def Hello(Sum):
fori in Sum:
print(i)
S=("Hii", "Hello", "Namaste")
Hello(S)(a)
*****************************************
Functions Important Questions Answer Keys
-
(b)
< class 'type' > -
(b)
a b c d
-
(d)
Method
-
(a)
Id() returns the identity of the object
-
(c)
[3,5, 20, 5, 25, 1, 3]
-
SCHOOLbbbbCOM
-
A global variable is a variable that is accessible globally. A local variable is one that is only accessibleto the current scope, such as temporary variables used in a single function definition. A variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function where as local variable can be used only inside the function. We can access by declaring variable as global A.
-
Option (i) and (iv) are possible
PICKER maxval = 3, minval = 0 -
1. using import
Syntax:
import < modulename1 >[,, < modulename2>,....
Example:
import math, cmath
2. using from
Syntax:
from < module name > import < function1 >[, < function2 >,...... < functionn > ]Example:
from fib import fib, fib2 -
S.NO Parameters Arguments 1 Values provided in function header Values provided in function call 2 (eg) def area (r) : --->r is the parameter (eg) def rnain ()
radius = 5.0
area (radius)
--->radius is the argument
-
Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value.
-
If there is a function with many parameters and we want to specify only some of them in function call, then value for such parameters can be provided by using their names instead of the positions. These an; called keyword arguments.
(e.g.) def simpleinterest(p, n=2, r=0.6):
def simpleinterest(p, r=0.2, n=3): -
It is easier to use since we need not to remember the order of the arguments.
We can specify the values for only those parameters which we want, and others will have default values. -
import math.
def generatesq (n):
for i in range (100, n):
yield (math. sqrt (i)) -
1. It reduces complexity of the program.
2. It creates well-defined boundaries within the program.
3. It increases the reusability of the module. -
Built in functions are predefined functions that are already defined in Python and can be used anytime. e.g. len(), typet), int(), etc. User defined functions are defined by the programmer.
-
Built-in functions are predefined functions that are already defined in Python and can be used anytime e.g. len(), type(), int() etc. Functions defined in modules are predefined in modules and can be used only when the corresponding moduleis imported
e.g. to use predefined function sqrt() the math module needs to be imported as import math. -
# Number system converter
import math
num=int (inputf''Enter a number:")
printt''Number entered = ", num) ,
octnum = oct(num)
hexnum= hex(num)
uninum= unicode(num)
asciinum= str(nurn)
print ("Octal equivalent", octnum)
print ("Hexadecimal equivalent" , hexnum)
print ("Unicode of number:", uninum)
print ("ASCIIcode of number:", asciinum) -
i) 2-y * (math.exp(2*y))+4*y
ii) math.fabs(exp(x)-x**2-x) -
# Program to calculate area of a triangle
import math
def artriangle (a.b,c):
"""This will use Heron's formula."?"
s=(a+b+c)/2
area=math.sqrt (s"(s-a)"(s-b)*(s-c))
return area
Fside=float (raw_input ("Enter first side:"))
Sside=fl.oat(raw_input("Entersecondside:"))
Tside=float(raw_input("EnterThirdside:"))
print ("Area of the triangle with sides", Fside, Sside,Tside, "is:",artriangle (Fside,Sside, Tside) -
import math:When we use import math statement, a new namespace is setup with the same name as that of the module and all the code of the module is interpreted and executed here Now all the defined functions and variables of the module are available to the program.
from math import:When we use from math import" statement no new namespace is created. All the functions and variables of the imported module are added to the namespace of the program. Now if there are two variables with same name, one in the program and other in the imported module then the variable of imported module is hidden by the program variable. -
output:
This will print something.
Hello!
This happens because when we import a module its main program is executed so first the statement print ("This will print something") is executed and then print calculate greet is executed. -
In Python, a block is executed in an execution frame. It contains:
*internal information for debugging
*name of the function
*values passed to the function
*variables created within function
*information about the next instruction to be executed. -
When immutable type objects are given as arguments then their value can not be altered by the function (i.e. only value is passed to the function) but when mutable type objects are passed their reference is passed and hence the values can be altered.
-
Positional arguments or Required arguments are those which must be provided for all parameters. The values of arguments are matched with parameters position wise.
-
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
-
A parameter having default value in the function header is known as a default parameter. A parameter can be specified as default only if all the parameters on its right are specified as default. To specify a default parameters syntax is
def < function header >(argl, arg2---arg x = < value > ):
arg x will now be a default parameter with default value as the value specified. -
(i) Valid as the arguments are used as keywords and rest are default arguments
(ii) Invalid as required argument p is not specified.
(iii) Invalid as two values for' p' are specified. One is positional and other is named. -
Whenever a name reference is encountered in a program, Python follows name resolution rule or LEGBrule. For every variable Python
(i) Check within its Local environment (legb), and uses it if available. Otherwise it moves to Enclosing environment.
(ii) Then checks the Enclosing environment (legb) and uses it.if available. Otherwise it moves to Global environment.
(iii) Now it checks the Global environment (legb) and uses the variable if available otherwise it moves to Built-in Environment.
(iv) At last it checks the Built-in environment (legb) and uses the variable otherwise it reports the following error:
name < variable = not defined. -
(a) This code will produce an error as in line 2 there is no value of a available to be used in RHS of the assignment statement.
(b)1. -
total=0
def sum (argl, arg2):
total=argl +arg2
print("Total:", total)
return total
sum (10,20)
print("Total:", total) -
It will print nothing as before reaching the print statement, the program control encounters the return statement.
-
1
None
1
(b) num=1
def myfunc():
num=10
returnnum
print (num)
print (myfunc())
print (num)
1
10
1
(c) num=1
def myfunc():
globalnum
num=10
returnnum
print (num)
print (myfunc())
print (num)
1
10
10
d) a=10
y=5
def myfunc():
y=a
a=2
print ry="y,"a=",a)
print ("a+y=", a+y)
return a+y
print ("y=", y,"a=",a)
print (myfunc())
print ("y=", y, "a=",a)
Ans. Local variable name 'a' not defined.
e) def multiply (num1, num2):
ans=num1 *num2
print(num1, "times", num2, =", ans)
return(ans)
output=multiply (5,5)
Ans. 5 times 5 = 25
f) def first (s,i):
return s * second (i)
def second (n):
return n+3
print (first('*',2))
Ans. ***** 2
g) def add (a,b):
return a+b
def mul (a,b=5):
return a*b
def square (x):
return mul (x,x)
print (add (4, square(mul(2))))
print (add (4,square(square(2))))
print (4, squaretsquare(2)))
104
20
416
h) def execute (x,y = 200):
temp = x+y
print (temp, x,y)
a,b =50,20
execute (b)
execute (a,b)
execute (b,a)
Ans. 220 20 200
70 50 20
70 20 50
i) def execute (x,y= 200,z= [23,]):
temp=x+y+z[o]
print (temp, x, y)
a,b =50,20
c=[10,]
execute (b)
execute (y=a,x=b)
execute (x=b, 2= [a,],y=a)
Ans. 243 20 200
93 20 50
120 20 50 -
def volBox(len=1, wid=1, hei=1):
volume =len *wid*hei
return(volume) -
def calcCube(num = 2):
cube = num **3
print ("Cube of", num, "is", cube)
return -
def checkstring (str1, str2):
if len (str1) = =len(str2):
return (True)
else:
return (False) -
def nthRoot(x, n=2):
res=x**(l/n)
return res -
def mindigit (numl, num2):
if (numl) < (num2)::
return num1
else:
return num2 -
def calcsquareDigits(num):
sum = ((num% 100)**2)+ (int((num/l00))**2)
print ("sum of squares of first two and last two digits is",sum)
return -
a = 5
b=9
def swap(c,d):
return d,c
swap(a,b) -
You can define functions to provide the required functionality. Here are simple rules to define a function in Python:
(1) Function blocks begin with the keyword def followed by the function name and parentheses ().
(2) Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
(3) The first statement of a function can be an optional statement, the documentation string of the function or docstring.
(4) The code block within every function starts with a colon (:) and is indented.
(5) The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. -
It gets the length of the string that you pass to it then returns it as a number.
-
hello ()
world () -
Return x raised to the power y. In particular, pow(1.0, x) and pow(x, 0.0)always return 1.0,even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError.
-
A 'module' is a chunk of python code that exists in its own (.py) file and is intended to be used by python code outside itself. Modules allow one to bundle together code in a form in which it can easily be used later.
The modules can be 'imported' in other programs so the function and other definitions in imported modules becomes available to code that imports them. -
The predefined functions that are always available for use are known as python's built-in functions.
For example:
len(), type (), int (), raw_input () etc. -
Python's built in function help ( ) is very useful. When it is provided with a program-name or a module-name or a function-name as an argument, it displays the documentation of the argument as help. It also displays the docstrings within its passed-argument's definition.
For example:
help (math)
will display the documentation related to module math. -
math module is used for mathematics related functions and random module implements pseudo-random number generators for various distributions.
-
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particularidentifier. There are two basic scopes of variables in Python:
(1) Global variables
(2) Local variables -
The function's header has colon missing at the end.
So add colon (:) at end of header line.
Thus, the correct code is
def minus (total, decrement) :
output = total- decrement
return output -
The output would be: 1.0
random.random( ) would generate a number in the range (0.0, 1.0) but math.ceil ( ) will return ceiling number for this range, which is 1.0 for all the numbers in this range.
Thus the output produced will always be 1.0. -
Here, function name contains spaces. But function name should be a valid Python identifier with no spaces in between. And here, no variable is defined to obtain value being input. Lines 4 and 6 are badly indented; being part of same function, those should be at the same indentation level as that of lines 2, 3, 5 and 7. And also, variable favourite-game is an invalid identifier as it contains a hyphen, but it should have been an underscore.
-
def area_circle ():
import math
diameter= float (raw_input ("Enter the diameter in Inches))
radius = diameter/2
area_circle_inches = (math.pi) * (radius * * 2)
print ("The area of circle",area_circle_ inches,"sq inch")
return (area_circle_inches) -
The output will show an error at line 5 as: NameError: name In'is not defined
-
The globals( ) and locals( ) functions can be used to return the names in the global and local namespaces depending on the location from where they are called. If Iocals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.
-
A docstring is just a regular python triple- quoted string that is the first thing in a function body or a module or a class. When executing a function body the docstring does not do anything like comments, but Python stores it as part of the function documentation. This documentation can later be displayed using helpt) function. So even though docstrings appear like comments but these are different from comments.
-
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the. program body by all functions. When you call a function, the variables declared inside it are brought into scope. -
You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword, lambda functions haye their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
-
(i) and (ii) are void function
(iii) and (iv) are non-void functions -
Docstrings are different from comments because docstrings are stored as documentation of the corresponding module or function or class and can be displayed using helpt) function with name of the corresponding module/ function/class as parameter e.g. help (math), help(math.pow) etc. This is not true with comments.
-
Output
Hii
Hello
Namaste