Functions Q&a
Functions Q&a
def func2():
A=5
FUNCTIONS
A=2
print("Value inside function:",A)
func2()
QUESTION
print("Value outside function:",A)
OUTPUT:
Value inside function: 2
Value outside function: 5
AND ANSWER
Here, we can see that the value of A is 5 initially. Even though the function func2() changed the value of A to 2,
it did not affect the value outside the function.
This is because the variable A inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value
of variables outside the function, they must be declared as global variables using the keyword global.
Example: Output:
1. Name the built-in mathematical function / method that is used to return an absolute value of a number.
Ans: abs()
2. Find and write the output of the following python code:
def myfunc(a):
a=a+2
a=a*2
return a
print(myfunc(2))
Ans:8
3. What is the default return value for a function that does not return any value explicitly?
Ans: None
4. Name the keyword use to define function in Python.
Ans: def
5. Predict the output of following code snippet:
def function1(a):
a=a+’1’
a=a*2
function1(‘Hello’)
Ans: Hello1Hello1
6. Variable defined in function referred to _________variable.
Ans: local
7. Name the argument type that can be skipped from a function call.
Ans: default arguments
8. Positional arguments can be passed in any order in a function call. (True/False)
Ans: False
9. Which of the following is function header statement is correct.
a. def fun(x=1,y) b. def fun(x=1,y,c=2) c. def fun(a,y=3)
Ans: c. def fun(a,y=3)
10. Predict the output of following code snippet.
def printDouble(A):
print(2*A)
print(3)
Ans: 3
1. What is the difference between a Local Scope and Global Scope ? Also, give a suitable Python code to illustrate
both.
Ans: A name declared in top level segment ( main ) of a program is said to have global scope and can be used in
entire program.
A name declare in a function body is said to have local scope i.e. it can be used only within this function and the othe
block inside the function.
Global=5
def printDouble(A):
Local=10
print(Local)
print(Global)
3. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with each
correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
Ans:
def result_even( ):
x = int(input(“Enter a number”))
if (x % 2 == 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
result_even( )
4. Differentiate between Positional Argument and Default Argument of function in python with suitable
example
Ans: Positional Arguments: Arguments that are required to be passed to the function according to their position in
the function header. If the sequence is changed, the result will be changes and if number of arguments are
mismatched, error message will be shown.
Example:
def divi(a, b):
print (a / b)
>>> divi(10, 2)
5.0
>>> divi (10)
Error
Default Argument: An argument that is assigned a value in the function header itself during the function
definition. When such function is called without such argument, this assigned value is used as default value and
function does its processing with this value.
def divi(a, b = 1):
print (a / b)
>>> divi(10, 2)
>>> 5.0
5. Ravi a python programmer is working on a project, for some requirement, he has to define a function with
name CalculateInterest(), he defined it as:
def CalculateInterest (Principal, Rate=.06,Time): # code
But this code is not working, Can you help Ravi to identify the error in the above function and what is the
solution.
Ans: In the function CalculateInterest (Principal, Rate=.06,Time) parameters should be default parameters from
right to left hence either Time should be provided with some default value or default value of Rate should be
removed.
6. Predict the output of the following python code:
def guess(s):
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'#'
print(m)
guess("welcome2kv")
Ans: vELCcME#Kk
7. What is the meaning of return value of a function? Give an example to illustrate its meaning.
Ans: Return value of a function is the value which is being given back to the main
program after the execution of function.
e.g.
def Check():
return 100
8. Differentiate between call by value and call by reference with a suitable example for each.
Ans: In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-
value because you can not change the value of the immutable objects being passed to the function. Whereas passing
mutable objects can be considered as call by reference because when their values are changed inside the function, the
will also be reflected outside the function.
9. Find and write the output of the following Python code:
def Show(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Show('HappyBirthday')
Ans: hAPPYbIRTHDAY
10. Rewrite the following code in python after removing all syntax errors. Underline each correction done in the
code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
elseif i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
Ans:
def func(a): #def
s=m=n=0 #local variable
for i in range(0,a): #range function missing
if i%2==0:
s=s+i
elif i%5==0: #elif and colon
m=m+i
else:
n=n+i
print(s,m,n) #indentation
func(15)
Application Based Questions (3 Marks)
1. Write a function listchange(Arr)in Python, which accepts a list Arr of numbers , the function will replace the
even number by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:
a=[10,20,23,45]
listchange(a,4)
output : [10, 10, 115, 225]
Ans:
def listchange(arr,n):
l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5
a=[10,20,23,45]
listchange(a)
print(a)
2. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers
and n is a numeric value by which all elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output
Arr = [30,40,12,11,10,20]
Ans:
def LShift(Arr,n):
L=Arr[n::]
R=Arr[:n:]
Arr=L+R
print(Arr)
3. Write a function REP which accepts a list of integers and size of list and replaces elements having even values
with its half and elements having odd values with twice its value. eg: if the list contains
3, 4, 5, 16, 9
then the function should rearranged list as
6, 2,10,8, 18
Ans:
def REP (L, n):
for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
4. Write a function which accept the two lists, and returns a list having only those elements that are common
between both the lists (without duplicates) in ascending order.
Make sure your program works on two lists of different sizes. e.g.
L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
The output should be:
[1,2,3,5,8,13]
Ans: L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
L3=[]
temp_L1=list(set(L1))
temp_L2=list(set(L2))
for i in temp_L1:
for j in temp_L2:
if i==j:
L3.append(i)
L3.sort()
print(L3)
5. Write a user defined function countwords() to accept a sentence from console and display the total number of
words present in that sentence.
For example if the sentence entered by user is:
“Living a life you can be proud of doing your best.” then the countwords() function should display the output
as:
Total number of words : 11
Ans:
def countwords():
sen = input(“Enter a line : ”)
z = sen.split ()
print ("Total number of words:", len(z))
Chapter – 3 Working with Functions
Ans: - It is a sub program that perform some task on the data and return a value.
Q.2) Write a python function that takes two numbers and find their product.
return (X*Y)
Q.3) Write a python function that takes two numbers and print the smaller number. Also write how to
call this function.
if(A<B):
print(“Smaller No – “, A)
else:
print(“Smaller No – “, B)
a=int(input(“Enter a number:”))
SMALLER(a,b)
Q.4) How many values a python function can return? Explain how?
def square_and_cube(X):
a=3
x,y,z=square_and_cube(a)
print(x,y)
return (p*r*t)/100
7|Page
Ans: - def SI(p, r, t=2):
return(p*r*t) /100
Q.6) Write a small python function that receive two numbers and return their sum, product, difference
and multiplication and modulo division.
calling of function: -
a,b,c,d,e=ARITHMATIC_OPERTAIONS(3,4)
print('Sum=',a)
print('Product=',b)
print('Difference=',c)
print('Division=',d)
print('Modulo Division=',e)
Ans: - Part of program within which a name is legal and accessible is called scope of the variable.
Ans – Global Scope – A name declared in top level segment of a program is said to have global scope
and it is accessible inside whole programme.
Local Scope – A name declared in a function body is said to have local scope and it can be used only
within this function.
print(B)
print(A)
Q.9) Consider the following function headers. Identify the correct statement: -
n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(2,1)
CALLME(3)
Ans: - 2 4
23
64
***
9|Page
Chapter-4 Python Library
Q.1) What is Libraries in Python and How many types of main library use in Python?
Ans: -A Library is a collection of modules that together caters to specific types of needs
or applications. Like NumPy library of Python caters to scientific computing needs.
Ans: - We can import a library in python program with the help of import command.
import pandas as pd
Statements
Z=(x+y)/2
Print(Z)
Q.4) Create a function in Python to calculate and return Area of rectangle when user
enters length and bredth.
Return(a*b)
Ans: - A module is a file with .py extension that contains variables, class definitions,
statements and functions related to a particular task.
Q.7) Create a package Arithmetic Operations(named AO) contain sum, product and
difference of two numbers and use it in your main programme.
10 | P a g e
return (X+Y)
def PRODUCT(X,Y):
return(X*Y)
def DIFFERENCE(X,Y):
return(X-Y)
Now lets save this file as AO.py then our module is created now.
import AO
n1=int(input(‘Enter a Number’))
n2=int(input(‘Enter another Number’))
print(‘Sum = ‘, AO.ADD(n1,n2))
print(‘Difference=’,AO.DIFFERENCE(n1,n2))
print(‘Product=’,AO.PRODUCT(n1,n2))
Output: -
11 | P a g e