Chapter 2 Function
Answers of Unsolved Questions
Q1. A program having multiple function is considered better designed than a program without any function. Why?
Answer:
A program having multiple function is considered better designed than a program without any function because-
Reusable functions can be put in a library in modules-
We can store the reusable functions in the form of modules. These modules can be imported and used when needed in other programs.
Redundant code is at one place, so making changes is easier-
Instead of writing code again when we need to use it more than once, we can write the code in the form of a function and call it more than once. If we later need to change the code, we change it in one place only. Thus it saves our time also.
The program is easier to understand-
Main block of program becomes compact as the code of functions is not part of it, thus is easier to read and understand.
Q2. Write a function called calculate_area() that takes base and height as input arguments and returns area of a triangle as an output.
The formula used is (Triangle Area = 1/2*base*height)
Answer:
def calculate_area(x , y) :
return 1 / 2 * x * y
base = float(input("Enter the Base of triangle:"))
height = float (input ("Enter the Height of triangle:"))
print ("Area of Triangle is:", calculate_area(base , height))
Q3. Modify the above function to take a third parameter called shape type. Shape type should be either triangle or rectangle. Based on the shape, it should calculate the area.
The formula used is Rectangle area= length* breadth
Answer:
def calculate_area(x , y , z) :
if z == "rectangle" :
print ("Area of Rectangle : - ", x * y)
elif z == "triangle" :
print ("Area of Triangle is : - ", 1 / 2 * x * y)
else :
print ("Error :( ")
shape = input("Enter the Shape (rectangle OR triangle)=")
base_or_length = float(input("Enter the 'Length or Base' ="))
height_or_width = float (input ("Enter the 'Height or width'="))
calculate_area(base_or_length , height_or_width , shape)
Q4. Write a function called print_pattern that takes integer number as argument and prints the following pattern.
If the input number is 3.
*
* *
* * *
If input is 4, then it should print:
*
* *
* * *
Answer:
def print_pattern (x) :
for i in range (1, x + 1) :
print (i * "*")
num = int (input ("Enter the number : - "))
print_pattern (num)
Q5. What is the utility of: -
(i) default arguments (ii) Keyword arguments?
Answer:
(i) A parameter having a default value in function header becomes optional in function call. Functions call may or may not have value for it.
(ii) Keyword arguments are the named arguments with assigned values being passed in the function call statement.
Q6. What are operators? Give examples of some unary and binary operators.
Answer:
Operators are used to perform some specific task on operands.
Example of unary operator: -
+ unary plus , - unary minus etc.
Example of binary operator:
+ addition ,- subtraction etc.
Q7. Describe the different styles of functions in Python using appropriate examples.
Answer:
1. Built-in functions: These are pre-defined functions and are always available for use.
For example: len(), type(), int(), input() etc.
2. Functions defined in modules: These functions are pre-defined in particular modules and can only be used when the corresponding module is imported.
For example: if you to use pre-defined functions inside a module, say sin(), you need to first import the module math (that contains definition of sin() ) in your program.
3. User defined functions: These are defined by the programmer. As programmers you can create your own functions.
Q8. What is scope? What is the scope resolving rule of Python?
Answer:
Parts of program within which a name is legal and accessible, is called scope of the name.
• The scope resolving rule of Python is LEGB rule.
LEGB Rule : The acronym stands for Local, Enclosing, Global, and Built-in, which represent the four levels of variable lookup.
Local (L): The local scope refers to the current function or code block. When a variable is referenced within a function or code block, the interpreter first checks the local scope to see if the variable is defined there. If found, it uses that value.
Enclosing (E): The enclosing scope refers to the scope of the function or code block that contains the current function or code block. If the variable is not found in the local scope, the interpreter checks the enclosing scope to see if the variable is defined there. This process continues until the variable is found or the global scope is reached.
Global (G): The global scope refers to the module-level scope. If the variable is not found in the local or enclosing scopes, the interpreter looks for it in the global scope. Variables defined outside any functions or code blocks are in the global scope.
Built-in (B): The built-in scope refers to the pre-defined names and functions available in Python. If the variable is not found in any of the previous scopes, the interpreter checks the built-in scope. This includes built-in functions like print() or len().
The LEGB rule defines the order in which these scopes are searched when a variable is referenced. It helps in understanding how Python resolves variable names and allows you to have variables with the same name in different scopes without conflicts.
Q9. What is the difference between local and global variables?
Answer:
Local variable:
• It is a variable which is declared within a function or within a block.
• It is accessible only within a function/block in which it is declared.
Global variable:
• It is variable which is declared outside all the functions.
• It is accessible throughout the program.
Example:
def sum( ):
a = 20 # Here a is local variable
b = 30 # Here b is local variable
print("Value of a in function = ",a)
print("Value of b in function = ",b)
su = a+b
return su
a =10
print("Value of a out of function Example of Global variable=",a)
print("Sum of a and b ",sum())
print("Value of a out of function Example of Global variable=",a)
Q10. 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.
Answer:
(a) Parameter.
(b) Keyword argument.
(c) Argument.
(d) Default argument.
(e) Keyword argument.
(f) Global variable.
(g) Local variable.
Q11. Consider the following code and write the flow of execution for this. Line numbers have been given for your 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
Answer:
1->5->9->10->5->6->1->2->3->6->7->10->11
output: 25
Q12. What will the following function return?
def addEm(x, y, z):
print (x+ y + z)
Answer:
It is a void function.
So, it will return None.
Q13. What will be the output displayed when addEM() is called/executed?
def addEm(x, y, z):
return x + y + z
print (x+ y + z)
Answer:
When function called then it will add all the argument and it will show nothing.
Q14.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!")
Answer:
(i)
Output:-
1
Error: - NameError: name 'myFunc' is not defined
(ii)
Output:-
1
10
1
(iii)
Output:-
1
10
10
(iv)
Output:-
Hello there!
Q15. 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:
Output:-
y = 5 a = 10
Error
Q16. 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:
When function called then it will add all the argument and it will show no result.
Q17. 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") :)
Answer:
(a)
def minus (total, decrement):
output = total - decrement
print(output)
return (output)
(b)
def check():
N = input ("Enter N: ")
i = 3
answer = 1 + i ** 4 / N
return answer
(c)
Calling of function is in wrong way. If that is corrected then it will show no error.
def minus (total, decrement):
output = total - decrement
print(output)
return (output)
(b)
def check():
N = input ("Enter N: ")
i = 3
answer = 1 + i ** 4 / N
return answer
(c)
Calling of function is in wrong way. If that is corrected then it will show no error.
Q18. Define flow of execution. What does it do with functions?
Answer:The flow of execution refers to the order in which statement are executed during a program run.
It do nothing with functions.
Q19.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.
Void Function :- Which Function do not return any value.
Non Void :- Which Function return value.
def rup(doll) : #void
print("(void ) rupees in ",doll ,"dollar = ",doll * 72)
def rupee(doll) : # non Void
return doll * 72
doll = float(input("Enter dollar : "))
rup(doll) #void
print("( non void ) rupees in ",doll ,"dollar = ", rupee(doll) ) # non Void
Q20.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
Answer:
def vol( l = 1, w = 1 , h = 1 ) :
return l * w * h
length = int(input("Enter the length : "))
width = int(input("Enter the width : "))
height = int(input("Enter the height : "))
print("volume of box = ", vol( length , width , height ))
Q21.Write a program to display first four multiples of a number using recursion. (Now not in syllabus)
Answer:
def multi(n,x):
if x == 4 :
print(n*x)
else :
print(n*x,end =",")
multi(n,x+1)
num = int(input("Enter a number :-"))
multi(num,1)
Post a Comment
Post a Comment