Adobe Scan Oct 17, 2024
Adobe Scan Oct 17, 2024
CHAPTER
Functions
function 1) #call
return
# main script
After completing the
functionl) script function will pass
print the control to main
script.
66 ogether itk Conputer Science (Python)-12
9. Scope (of a variable). Scope of' avariable refers to
the Output produced by this module is:
part of the module wherc it can be used. A variable can a= 5
have local scope or global scope. a= 50
COMMON INSTRUCTIONS
Assertion and Reason Questions
(a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct
explanation of Assertion (A)
(b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct
explanation of Assertion (A)
(c) Assertion (A) is true but Reason (R) is false
(d) Assertion (A) is false but Reason (R) is true
(i) Keyword return is used to return a value from a Mutable data objects Immutable data objects
functions
function. are passed to functions are passed to
with reference. with value.
For example, return 10
Examples of mutable Examples ofimmutable
3. What is the use of keyword global? data objects are: lists data objects are:
and dictionaries. integers, floats, strings,
Keyword global is used to:
tuples.
(i) Specify the global variable(s) which will be used
in the function even if their values are changed in 33. Rewrite the following python code after removing any/
the function.
all syntacticalerrors with each correction underlined:
(a) def guess ()
(i) Tocreate global variable(s) in the function. print ("Hello")
32. Differentiate between: print (a)
a-5
(a) Formal parameters and Actual parameters
var-2
(6) Local variable and global variables quess
(c) Mutable and immutable data objects (6) def add:
total=0
AnS. (a) Formal Parameter Actual parameter
n=input("Enter a number: "
Specified in the Specified the
m=input("Ente another number:)
function header. function call.
total=m+n
Can be a variable only Can be a variable,
constant, or any valid print total
expression add()
For example: (c) Def func (a+b):
display (a): # a is fOrmal parameter tot-a+b
def
a = a * 2 # increment by 2 print(tot)
m=10
print("a=", a)
n=20
x=5
display (x) #x is actual parameter fun (m, p)
(d) function f1(b):
Local yariable Global variable if b>0 then:
(b)
return"Positive"
Defined insíde a Defined outside any
function without using function, or inside else return "Not Positive"
the keyword global. a function using the m=int (input("Enter an number: "))
keyword global. msg=f1()
Can be used only Can be used throughout print (msg)
inside the function in the module, after its (e) def isMultiple (a b):
which it is declared. declaration.
if a%b=0:
For example: return true
a 5 # global variable else return false
def display () : m=int(input("Enter first number: "))
a = a * 2 # Local Variable n=int(input ("Enter second number: "))
print ("Display() inside:", a) if isMultiple [m, n]:
display() print ("m is a multiple of n")
a multiple
of n")
else print (m, "is not
Functions 73
hello X += temp
if(y!=200):
40. Write the output of the following Python code : print(temp, x, x)
def Update (X=10): a=20
X += 15 b=10
func (b)
print('X = ', x) print(a, b)
X=20
func(a, b)
Update() print (a, b)
print("'X = ', X) Ans. 110 120 120
Ans. X = 25 20 10
X= 20 30 50 50
20 10
41. Write the output of the following Python code:
def div5 (n): 44. Write the output of the given code:
if n%5==0: def Convert (0ld) :
return n*5 l=len (0ld)
New="n
else:
for i in range (0,1):
return n+5
if 0ld[i].isupper():
def output (m=5): New=New+0ld[i]. lower()
for i in range (0,m): elif 0ld [i].ilower () :
print (div5 (i), 'e' , end="") New=New+0ld[i].upper()
print () elif 0ld [i].isdigit() :
output (7) New=New+"*
else:
output()
output (3) New-New+"%"
return New
Ans. 0@6 @7 @8 @9 @25 @11 @ 0lder-"InDIag2020"
0 @6 @7 @8 @9 @ Newer=Convert (0lder)
print ("New string is :" Newer)
0@6 @7 @ Ans. New string is :
42. Write the output of the following Python code:
iNdiA%****
45. Write the output of the
def func (b): given code:
qlobal x def display (n):
print('Global x=', x) Sum=5
y = X+ b i = 1
X = 7 while i<-n:
Z X-b Sum += j
print("Local x ',x) i +=5
Sum=sum-2
Functions 75
print("Value =", sum," i: ",i) 48. Write the output of the given codex=
X = 30 7 #Global Variable
display (x) def display():
Ans. Value = 74 /= 31 global x
X=10
46. Write the output of the given code:
if x>=7:
X = 15
y=9
def change(): print (y)
#using a global keyword display()
global x print (x)
# increment value of a by 5
Ans, 9
X X + 5
10
print("Value of x inside a function :", x)
change() 49. Find the errors and rectify the script.
print ("Value of x outside a function :", x) def show(n, string='Good' k=5):
Ans. X = 15 return display (string)
def change(): return n
#using a global keyword def display (string)
global x 4return string==str(5)
# increment value of a by 5 print (show("Children's Day"))
e'):) Tree i))
X = X + 5 print(display (string='true'
print("Value of x inside a function :", x) print (show(5, "Good") )
change() Ans. Correct Code
print("Value of x outside a function :", x)
# Python program to modify a global
def show(n,string='Good', k=5):
return display (string)
# value inside a function
return n # Cannot return 2 values
X = 15
def display (string) :
def change(): return string==str(5) # indentation
#using a global keyword
global x
# increment value of a by 5
print (show("Children's Day"))
X = X + 5
print (display(string='true'))
# to be removed
print("Value of x inside a function :". x) print (show(5, "Good"))
change ()
print("Value of x outside a function :", x) 50. Find the output:
Value of x inside a function : 20 def show(n,string=' Good' ,k=5):
Value of x outside a function : 20 return display (string)
return n
47. Write the output of the given code
def Check(K, L=70): def display (string):
return string==str(5)
if (K>L):
K-=L print (show("Children's Day"))
else: print (display(string='true'))
K+=L print (show(5, "Good") )
M=100 Ans, False False False
N=40
51, Write a function Display) which do not accept any
Check(M, N) parameter and return none.
print (M, "#", N)
Ans. def display(): def display ():
Check(M)
print (N,"*",M)
Ans. 100 # 40
printl) print()
return none
print()
print (display () )
40 # 100 print(display () )
76 Togetker ucek Computer Science (Python)-12 age and
(c) A function Vote Casting) will acceptsvalue.
52. Answer the following questions based on the given citizen as parameter returns
Boolean
parameters and
seript/code. (d) A function Show ) accepts no
def show(a) : returns nothing.
a=10
Ans. (a) def ADD (a, b) :
a=a+3 (b) def ADD (a, b):
return a
return a
b=100
citizen):
res-show(b) (c) def Vote_Casting(age,
False
(a) Name the variable used as parameter. return True or retUIn
(6) Name the variable used as an argument (d) def Show() :
(c) Write function header statement. return None
() Which statement will return a value? script/code
(e) Name a local variable(s). 55. Write the output of the following
) Name a global variable(s). (a) def show5():
(e) Write function call statement. print ("Hello")
(h) Variable 'a' will return the value to variable show5a()
def show5a():
() Name formal parameter print ("Bye")
Ans. (a) a show5a()
(b) def show5():
(6) b print ("Hello")
(c) def show(a) : show5a()
(d) return a def show5a():
(e) a print("Bye")
show5()
(g) res=show(b) Ans. (a) Bye
(6) Hello
(h) res
() a Bye
given 56. Write a program to create the list and do the following
53. Answer the following questions based on the operations using the predefined functions.
seript/code.
def show4 (a,b): To print sum of all element of the list
print (a+b) To find maximum element of the list
X=show4(10, 15) To find minimum element of the list
print (x) To find the length of the list
(a) Name local variable(s).
To sort the list in ascending order
(b) Name global variable(s).
is built-in function. To sort the list in descending order
(c) [FileName:ch-datas\Q14|
is user-defined function.
(d)
1
(e) Name actual parameter(s). Ans. list = input('Enter the sorted list of numbers:
) Name formal parameter(s). list = list.split()
Ans. (a) a, b
list [int (x) foI X in list]
(b) x print (list)
(c) print(0 print(type (list)
(d) show4) print ("Sum of the list", sum(list))
max(list))
(e) 10,15 print("Maximum element in the list"., min(list))
() a, b print("Minimum element in the list"",
S4. Write the function definition for the following: print ("Length of the list", len(list))sorted(list))
order"",
(a) A function ADD) accepts two parameters. print ("Sorted list in ascending
(6) A function ADD) accepts two parameters and print ("Sorted list in descending
returns a single value. order",sorted(list.reverse=True))
Functions 77
57. WAP using function to get the largest number from Ans. # ilename: Ch-datas-p 010
a list using loop.
Ans. def maxlist( list ):
|FileName:ch-datas\Q22| def ZeroEnding (SCORES):
S=0
max = list[ 0 ] for i in SCORES:
for a in list: if 1%10- =0:
if a > max: S=S+i
max a print (s)
return max
lst=eval(input ("Enter the list")) 61. Write definition of aMethod COUNTNOWPLACES)
print (maxlist (1st) ) to find and display those place names, in which there
are more than 5 characters.
58, Write a user defined function arrangelements(X),that
accepts a list X of integers and sets all the negative For example:
If the list PLACES contains
elements to the left and all positive elements to the
right of the list. "DELHI", "LONDON'", "PARIS", "NEW
[FileName:ch-datas\Q23|
YORK", "DUBAI"I
For example:
The following should get displayed
if L=|1,-2,3,4,-5,7] ,
LONDON
Then the output should be: -2,-5,3,4,7] NEW YORK
Ans. def arrangelements (X): Ans. #Filename: Ch-datas -P_011
L=len(X) def COUNTNOW(PLACES):
for i in range (L): for P in PLACES:
if X[i]<0 and i! -0:
if len(P)>5:
j=i print (P)
while j! =0 and X[j-1]>0:
x[j],x[j-1]=X[j-1] ,x[i) 62. Write definition of a method OddSum(NUMBERS)
to add those values in the list of NUMBERS, which
j-j-1
are odd.
print (X)
Ans. #Filename : Ch-datas -P_013
59. Write the definition of a function Reverse(X) in
Python, to display the elements in reverse order def OddSun (NUMBERS):
the
such that each displayed element the twice of n=len(NUMBERS)
original element (element * 2) of the List X in the S=0
def createDict():
66. Write a python program using functions to do the
following task: a-{)
(a) To check whether the entered number is prime for i in range(5):
X=random. randint(65,90)
or not.
X=chr(x)
(b) To print all the prime number between the 2 to n.
n=random. randint(10,99)
Also write the python statements to execute these
Filename:ch3_Q10 a. update({x:n})
function.
Ieturn a
Ans. def isPrine (n):
#A number is prine if it is not divisible by
any number tpl=createTuple ()
from 2 to its square root print ("Tuple:",tpl)
p=True lst=createList()
d=2 print ("List",lst)
while d<=pow(n,0.5) and p: dict=createDict()
if n%d==0: print("Dictionary: ",dict)
p=false
else: d+=1 68. Write apython program using function to find greater
return p number between two numbers. The function should
def showPrime(n): take 2 numbers as parameters.
print("Prime numbers in the range 1 Filename: ch-3 Q12
to",n, "are: ")
for i in range(2, n+1):
Ans. def Greater (n1,n2) :
if n1>n2:
if isPrime (i) : #Calling isPrine () from
showPrine () print (n1,"is qreater")
prínt (i,end=" ") elif n2>n1:
print("To dísplay prine numbers from 1 to n:") print (n2,"is greater")
n=int(input("Enter the value of n: ")) else:
showPrine (n) print("numbers are equal")
67, Write a python program using function to demonstrate n1 eval(input("'Enter a number: )
)
random0) along with list, tuple and dictionary. n2 eval(input('EnteI another nunber:
for i in L1:
Ans. def countl(li, ml,m2):
if i in L2: ctr = 0
C. append(i) for x in range(len(li) ):
return c if m1 <= lilx] <= m2:
ctr += 1
85. WAP using function to insert new element in sorted
return ctr
list.
li-eval(input ("Enter the list"))
def insertnew(1ist, n):
m1=int (input("Enter the first limit"))
for i in range(1len (list) ): m2-int (input ("Enter the second linit"))
if list[i] > n: ans=countl(li, m1, m2) # Calling of function
index =i print("Total countt =",ans)
break
89, Write a Python program to push all zeros to the end
# Inserting n in the list of a given list a. The order of the elements should
list = list [ :1] + [n] + list[i:) not change.
print("New List", list) Input: Elements of the list with each element
# Main separated by a space.
Output: Elements of the modified list wìth each
li-eval(input ("Enter the List in ascending element separated by a space. After the last
order") ) element, there should not be any space.
ele=int(input("Enter the new element to be Example:
inserted")) Input:0 2 3 4 67 0 1
insertnew(1i, ele) Output:2 3 4 67 1 0 0
82 Together wcek Computer Science (Python)-12
cOunt +: 1
Ans. def pushZerosToEnd(arr, n):
#Main
9)
arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0,
count
for i in range(n): n = len(arr)
if arr[i] ! 0: pushZerosTo End (arr, n)
arr[count] = arr[i] end of
count+=1 print( "Array after pushing all zeros t0
while count < n:
array:")
print(arr)
arr[count] = 0