0% found this document useful (0 votes)
65 views11 pages

Functions Q&a

The document provides a comprehensive overview of Python functions, including definitions, types of arguments, variable scope, and examples of function implementations. It explains concepts such as local and global scope, built-in functions, and the differences between positional and default arguments. Additionally, it includes application-based questions with sample code to illustrate various programming tasks in Python.

Uploaded by

menakavision683
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views11 pages

Functions Q&a

The document provides a comprehensive overview of Python functions, including definitions, types of arguments, variable scope, and examples of function implementations. It explains concepts such as local and global scope, built-in functions, and the differences between positional and default arguments. Additionally, it includes application-based questions with sample code to illustrate various programming tasks in Python.

Uploaded by

menakavision683
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Example 2:

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:

Very Short Answer Type Questions (1-Mark)

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

Short Answer Type Questions (2-Marks)

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)

2. Define different types of formal arguments in Python, with example.


Ans: Python supports three types of formal arguments :
1) Positional arguments (Required arguments) - When the function call statement must match the number and order o
arguments as defined in the function definition. Eg. def check (x, y, z) :
2) Default arguments – A parameter having default value in the function header is known as default parameter. Eg.
def interest(P, T, R=0.10) :
3) Keyword (or named) arguments- The named arguments with assigned value being passed in the function call
statement. Eg. interest (P=1000, R=10.0, T = 5)

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

Q.1) Define a function?

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.

Ans: - def PRODUCT(X,Y):

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.

Ans: - def SMALER(A,B):

if(A<B):

print(“Smaller No – “, A)

else:

print(“Smaller No – “, B)

a=int(input(“Enter a number:”))

b=int(input(“Enter another number:”))

SMALLER(a,b)

Q.4) How many values a python function can return? Explain how?

Ans: Python function can return more than one values.

def square_and_cube(X):

return X*X, X*X*X, X*X*X*X

a=3

x,y,z=square_and_cube(a)

print(x,y)

Q.5) Rewrite the correct code after removing the errors: -

def SI(p, t=2, r):

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.

Ans: - def ARITHMATIC_OPERTAIONS(a,b):

return a+b, a*b, a-b, a/b, a%b

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)

Q.7) What is scope of a variable?

Ans: - Part of program within which a name is legal and accessible is called scope of the variable.

Q.8) Explain two types of variable scope with example.

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.

A=0 # global scope


8|Page
def fun1():

B=0 # local scope

print(B)

print(A)

Q.9) Consider the following function headers. Identify the correct statement: -

1) def correct(a=1,b=2,c): 2) def correct(a=1,b,c=3):

c) def correct(a=1,b=2,c=3): 4) def correct(a=1,b,c):

Ans: - c) def correct(a=1,b=2,c=3)

Q.10) Find the output of the following code: -

Ans: - def CALLME(n1=1,n2=2):

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.

Q.2) How we can import library in Python program?

Ans: - We can import a library in python program with the help of import command.

Eg: - import random

import pandas as pd

Q.3) Give the basic structure of user defined function.

Ans: - def <Function_name>(arguments):

Statements

Eg: - def MEAN(x,y):

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.

Ans: - def AREA(a,b):

Return(a*b)

Q.5) What is module in Python?

Ans: - A module is a file with .py extension that contains variables, class definitions,
statements and functions related to a particular task.

Q.6) Write the features of a module.

Ans: - 1) Modules can be reused in other programmes

2) It is independent group of code and data

Q.7) Create a package Arithmetic Operations(named AO) contain sum, product and
difference of two numbers and use it in your main programme.

Ans: - def ADD(X,Y):

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.

Now we are creating our main python file: -

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

You might also like