GR 12 CH 3 Working With Functions Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

CHAPTER – 3 – WORKING WITH FUNCTIONS

TYPE – A – Short Answer Questions / Conceptual Questions

1. A program having multiple functions is considered better designed than a program


without any functions. Why?
A program having functions is considered better designed because-
1) The program becomes easier to read
2) The program becomes less error prone
3) Complexity of program is reduced
4) Repetition of code is reduced
5)Making changes or updating is easier.

2. What all information does a function header give you about the function?
The function header is the first line of a function definition. It begins with the “def” keyword and
ends with a colon “:”. It specifies the name of the function and its parameters which are variables
that are listed within the parentheses of a function header.
def add(x,y); # function header
return x+y

3. What do you understand by flow of execution?

The flow of execution refers to the order in which statements are executed during a program run.
Statements are executed one at a time, in order from top to bottom. Function definitions do not
alter the flow of execution of the program, but remember that statements inside the function are
not executed until the function is called
Example:

4. What are arguments ? What are parameters ? How are these terms different yet related
? Give example.
The values being passed through a function-call statement are called arguments ( or actual
parameters or actual arguments). The values received in the function definition/header are called
parameters (or formal parameters or formal arguments)

5.What is utility of: (i) default argument, (ii) keyword argument &
6. Explain with a code example the usage of default argument and keyword argument.
Default Argument: It is a Parameter initialized with default value in function header or
definition. It is useful when
• Matching arguments are not passed in the function call statement
• Some argument always have same value.

Keyword Argument: Also known as named arguments. A value being passed during function call
with specified name is called Keyword argument. It is useful when
• Any argument can be taken or passed in any order during function call.

7. Differentiate the different styles of functions in Python using appropriate examples

8. Differentiate between fruitful function and non-fruitful function

9. Can a function return multiple values? Why?


Yes, a function can return multiple values in python. To return multiple values we need to do
followings:
• The return statement should be written like
return value1,value2,……..
• Values returned by function call should be stored in tuple or by specifying same no of
variables.
For Example:
def perimeter(r):
circle = 2*3.14*r
square = 4*r
triangle = 3*a
return circle,square,triangle

a=intinput((“Enter Length”))

c,s,t = perimeter(a)
print(“Perimiter of Circle”,c)
print(“Perimiter of Square”,s)
print(“Perimiter of Triangle”,t)

10. What is scope? What is the scope resolving rule of Python?


Scope determines the accessibility and validity of an identifier, function or piece of code within a
part or whole program.
Python follow naming resolution scope also known as LEGB rule, which are as given below:
• It checks within local environment
• It checks within execution environment
• It checks the global environment
• It checks it built in environment
11.What is the difference between Local Variable and Global Variable
Local Variable Global Variable

Can be accessible within a part of program Can be accessible anywhere within a program

Declared within a function or block Declared at top level segment of program

Its lifetime is function’s runtime Its lifetime is entire program runtime

12. When is global statement is used? Why is its use is not recommended?

13. Write the term suitable for the following description


(a)A name inside the parenthesis 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) Parameter
b) Keyword Argument
c) Argument or Actual Parameter
d) Default Argument
e) Keyword Argument
f) Global Variable
g) Local Variable

14. 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?
When a variable is accessible or valid only within a part of program, it is referred as local scope
of variable.
When a variable is accessible or valid inside the whole program, it is referred as global scope of
variable.
To access a global variable within a function we use global statement to declare it.
for example–
def sample()
global x
x=20
print(x)
x=10
print(x)
sample()
print(x)

OUTPUT
10
20
20

TYPE – B – Application Based Questions

Output:-

Total : 30

Total : 0

Output:-

21
2. Consider the following code and write the flow of execution for this. Line numbers have
been given for your reference.

3. What will the following function return?

def addEm(x, y, z):


print (x + y + z)

When arguments are passed in addEm(x, y, z) then it add all the arguments and print the result.
IT is non void Function. The following function will return the “None” subject.

4. What will the following function print when called? def addEm(x, y, z):

def addEm(x, y, z):


return x + y + z
print (x+ y + z)

Ans: When function called then it will add all the argument and it will show nothing.
Because return keyword will work before print statement.
5. What will be the output of 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!")

6. 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 =
y = 5 a = 10

Error

Explanation: - Because at first y and a are global variable so we cannot use y, a (variable)
directly in function.
If we want to use "y" and "a" in function, we have to write
global y
global a
before

y=a
a=2
print ("y =", y, "a =", a)
print ("a+y =", a + y)
return a + y

in Function
myfunc()

7. What is wrong with the following function definition?

def addEm(x, y, z):


return x + y + z
print("the answer is", x + y + z)

8. Write a function namely fun that takes no parameters and always returns None.

9. 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?
Ans:

10. Q. Consider the code below and answer the questions that follow:
def multiply(number1, number2):
answer = number1 * number2
return(answer)
print(number, '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?

Ans:

(i)It will show no result. Because return statement is written before print statement.
(ii)Variable is ‘answer’. And its value is 25.

11. Find the errors in 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") :)
12.Draw the entire environment, including all user-defined variables at the time line 10 is
being executed.
def sum(a, b, c, d): #1
result = 0 #2
result = result + a + b + c + d #3
return result #4
#5
def length(): #6
return 4 #7
#8
def mean(a, b, c, d): #9
return float (sum (a, b, c, d))/length() #10
#11
print (sum(a, b, c, d), length(), mean(a, b, c, d)) #12
Answer =
When line 10 executes then it must be call from line 12.
At first line 12 is created in global environment. Then it call sum and create local environment
within global environment. Then sum function return the values in global environment.
Then line 12 call length and create local environment within global environment. Then length
function return the values in global environment. Then line 12 call mean and create local
environment within global environment. Then mean function call sum and create nested local
environment. Then sum function return values in local environment. Then mean function call
length and create nested local environment. Then length function return values in local
environment.
Then mean function return values in line 12 in global environment.

13.Draw flow of execution for above program.


Answer =
1 --> 6 --> 9 --> 12 --> 1 --> 2 --> 3 --> 4 --> 12 --> 6 --> 7 --> 12 --> 9 --> 10 --> 1 --> 2 --> 3 -
-> 4 --> 10 --> 6 --> 7 --> 10 --> 12

14. 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
15. 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 =

16.
Q. Write a program with non-void version of above function and then write flow of
execution for both the programs.
Answer :-
Program –
def fun(x): #1
return (x ** 2) #2

print (fun(4)) #3
print (fun(6)) #4
print (fun(2+1)) #5
print (fun(4-3*2)) #6
print (fun(3-2)) #7
Flow of execution:
1 --> 3 --> 1 --> 2 --> 3 --> 4 --> 1 --> 2 --> 4 --> 5 --> 1 --> 2 --> 5 --> 6 --> 1 --> 2 --> 6 --> 7 -
-> 1 --> 2 --> 7
17. Q. What is the output of following code fragments?
(i)

(ii)

Answer =(i)Output:-
[1, 2, 3, [4]] [1, 2, 3, [4]]
(ii)Output: -[23, 35, 47, [49]]
23 35 47 [49]
True

TYPE – C – Question – Programming based Questions


Q. 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.

Answer :-
Void Function :- Which Function do not return any value.
Non Void :- Which Function return value.
2. 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.

Answer :-

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.

Answer :-

(i)
def cube( a = 2 ) :
print( "Cube of ", a ,"=" , a ** 3 )

num = input("Enter a number (For empty press Enter ) :")

if num == "" :
cube()
else :
cube( int (num) )
Output
Enter a number (For empty press Enter ) :9
Cube of 9 = 729
>>>
Enter a number (For empty press Enter ) :
Cube of 2 = 8
>>>
(ii)

def chr(char1,char2) :
if char1 == char2 :
return "True"
else:
return"False "

char1 = input("Enter a Char 1 : ")


char2 = input("Enter a Char 2 : ")
print(chr(char1,char2))
Output :-
Enter a Char 1 : Path
Enter a Char 2 : Walla
False
>>>
Enter a Char 1 : Path
Enter a Char 2 : Path
True
>>>

4. Q. 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.

Answer :-

5. Write a function that receives two string arguments and checks whether they are same-length
strings (returns True in this case otherwise false).

Answer :-

def chr(a , b) :
print( len(a ) == len(b) )

first = input("Enter First String :-")


second = input("Enter Second String :-")

chr(first , second )
Output :-
Enter First String :-Python
Enter Second String :-Portal
True
>>>
Enter First String :-Path
Enter Second String :-Walla
False
>>>
Enter First String :-ABCDE
Enter Second String :-VWXYZ
True
>>>
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.

Answer :-

def root(x , n = 2 ) :
print( x ** (1 / n) )

x = int(input(" Enter a number = "))


n = int(input("Enter nthRoot (For empty Enter 0 )= "))

if n == 0 :
root( x)

else :
root(x,n)
Output :-
Enter a number = 4
Enter nthRoot (For empty Enter 0 )= 2
2.0
>>>
Enter a number = 4
Enter nthRoot (For empty Enter 0 )= 0
2.0
>>>
Enter a number = 9
Enter nthRoot (For empty Enter 0 )= 3
2.080083823051904
>>>
Enter a number = 6541
Enter nthRoot (For empty Enter 0 )= 6
4.3245476976058095
>>>
7. Write a function that takes a number n and then returns a randomly generated number
having exactly n digits (not starting with zero)

eg ., if n is 2 then function can randomly return a number 10-99 but 07, 02 etc. are not valid two
digit numbers.

Answer:-

import random

def ran( x ) :
a = 10 ** (x - 1 )
b= 10 ** (x )
print( random.randint ( a , b ) )

n = int(input("Enter number of digit : "))

ran(n)
Output :-
Enter number of digit : 2
72
>>>
Enter number of digit : 9
638330587
>>>
Enter number of digit : 5
75450
>>>
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)].

Answer :-

def min(x , y ) :
a = x % 10
b = y % 10
if a <b :
return x
else :
return y

first = int(input("Enter first number = "))


second = int(input("Enter second number = "))

print ( "Minimum one's digit number = " , min( first , second ) )


Output :-
Enter first number = 491
Enter second number = 278
Minimum one's digit number = 491
>>>
Enter first number = 45656
Enter second number = 5418
Minimum one's digit number = 45656
>>>
Enter first number = 9674
Enter second number = 5431
Minimum one's digit number = 5431
>>>
Enter first number = 165
Enter second number = 634
Minimum one's digit number = 634
>>>
9. Write a program that generates a series using a function which takes first and last values
of the series and then generates four terms that are equidistant e.g., if two numbers passed
are 1 and 7 then function returns 1 3 5 7.

Answer :-

def ser( a ,b):


d = int ( ( b - a ) / 3 )
print("Series = " , a , a + d , a + 2*d , b )

first = int(input("Enter first Term = "))


last = int(input("Enter last Term = "))

ser(first , last )
Output :-
Enter first Term = 1
Enter last Term = 7
Series = 1 3 5 7
>>>
Enter first Term = 7
Enter last Term = 1
Series = 7 5 3 1
>>>

Enter first Term = 2


Enter last Term = 8
Series = 2 4 6 8

-------------------- ********************** -------------------------------

You might also like