0% found this document useful (0 votes)
18 views

Functions Assignment

Uploaded by

artdebjeetsaha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Functions Assignment

Uploaded by

artdebjeetsaha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Python Functions

2 that is
used to
perform

reusing.
a single, related action. Functions.

What function in python code


of
code
1. is a reusable

degree create yo
our own functicons.
Ans. A function is a block
of
organized,

a p p l i c a t i o n
and a high
etc.
but y o u
can
also
These f
bette modularity for your inctions
like print().
built-in
n gives many
called user-defined
functions. tion.
TunCO
are into a
parameters.
known as
TOu c a n pass data,
as a result.
function can return
data
A
in python function
What is the role of indentation to indicatethe start
(Space) in Python
Functions
end like
curly
braces

declaring indentatio
stop
Ans. Indentation
any
explicit begin or
necessary
that
while
ion, you u
tunctions don't have It is also
ython this
indentation.
have to rely on
unction, they for the rest of your
code.
maintain the s a m e indent

function?
to define user define
tion .in p.
3. How rules to define a functioa.
Function Here a r e simple
Ans. Defining a
the required
functionality.
parentheses ( ) .
define functions to provide function name and
YOu can
with the keyword
followed def
parentheses. You
by the
can also define.
Function blocks begin within these para
should be placed
parameters or arguments
Any input
inside these parentheses. documentation string of the fu-

function can be an optional


statement - the
The first statement of a

docstring. colon (:) and is indented.


function starts with a
T h e code block within every back an expression to the calle
[expression] exits a function, optionally passing
The statement return
return None.
A return statement with no arguments is the same as

Syntax
def functionname( parameters ):
function_docstring"
function_suite
return expression
How to call a function in python? Explain with an example.
Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def fun():
print("Hello")
un() # function calling
utput
ello
the output
5. GIve
defpmi
prin
t*t ******

print"hello")

pn
print hi
pm
printbye")

prm
Ans. hello

hi
***

bye

6. What is Parameter in python function?


Information can be passed to functions after the function name, inside tne
Ans. as parameter. Parameters are specified
parentheses. You can add as many parameters as you want. just separate them with a comma

7. What is the difference between parameter and argument?


Ans. Parameters are temporary variable names within functions.
The argument can be thought of as the value that is assigned to that temporary variable. For instance, lets consider
the following simple function to calculate sum of two numbers.
def sum(a.b):
return a+b
Sum(10,20)
a,b here are the parameter for the function 'sum
Arguments are used in procedure calls, i.e. the values passed to the function at run-time.10,20 are the arguments
for the function sum
8. What are the differnet types of Functions in python?
Ans. There are two basic types of functions: built-in functions and user defined functions.
The built-in functions are part of the Python language: for instance dir(), len(), or abs().
The user defined functions are functions created with the def keyword.
9. Explain the types of function arguments in python.
Ans. Function Arguments
You can call a function by using the following types of formal arguments

Required arguments Keyword arguments Default arguments Variable Number of Arguments


Arguments are passed as a dictionary.
) Required arguments: Required arguments are the arguments passed to a function in coTect positional orde
Here, the number of argunments in the function call should match exactly with the function definition.
def show(x.y)
print("Name is "x)
printAge is y)
show("Raj",18)
Output:
Name is Raj
Age is 18
Keyworda the argu b e c a u s e
the PylUl[

1S
arguments: identifies
order
( ) Kevword caller of
function
call, the out
a argument

n you
to place
pla with
parameters.

This allows y ou
values
match the
to
provided
def show(x.y):
print"Name is *x)

print("Age is *.y)
show(y=18,x="Raj")

OUTPUT
Name is Raj that
assumes a.default valu if
a
Age is 18
default
argument
is
example
an
argument
gives an idea on de value is
fault argumen
uments: A following
i) Default argur argument.
The
that
inthe function.call for
def sum(a.b=10):
print'sum is",a+b)
sum(15,25)
sum(15)
OUTPUT
Sum is 40
sum is 25
cases where you don t knoW the exact number aof argumen
IV) Variable number of arguments: In
can use the following syntax
with *args:
want to pass to a function, you
The variable stored in *args are represented in the form of tuple.
def change(*a):
for i in a
print(1)
print(a)
change(10,5)
change(15,20,25)
OUTPUT
10
5
(10, 5)
15
20
25
(15, 20, 25)
()Arguments are
passed as a
function. They are used when dictionary
you are not (**kwargs):
the function. sure of the Kwargs allow you to pass
Kwargs
asterisk notation (**)
can be used for number of
keyword keyword argur
In the
unpacking arguments
dictionary key, value pairs. This is that will
The
function, we use the
double asterisk ** done uSmg
arguments are
passed aas before the
same as the
parameter dictionary and these
excluding double asterisk ** arguments parameter name to denote
Example: this
def fun(** data):
make a
dictionary inside iuy
print(" nData type of
print(data)
for
argument:", type(data))
key, value in
print(key,value)data.items():
fun(Name"Aman'",Age=18,Marks=56)
10
Output:
<class 'dict'>
ot argument:
Data type 56}
Aman, 18, Marks:
"Age"':
Name
Name Aman

Age 18
wi"

Marks 5 0n , you
some
operations
function return Value? and try out
does a finction
0. How result of vour

to continue to work with the


S.if you Want
the return
statement to actually return a value
to use

Example
def square(x):

return x*x

print(squares)
print(square(a))

OUTPUT

9
25 ur
returm multiple values? Explain with an example. eonstructs a tuple and
retutt
function Python then
list of values and
a
1, Can
values should be a comma-separated
Yes,the return
1s.
this to the caller,
Ex:
def change(a.b.c.d):
m-max(a,b.c.d)

nmin(a.b.c.d)

s=atbtctd

return n,m.s
g.h.i-change(2,5,7,20)

print (g.h.i)
OUTPUT

2 20 34
OR

def change(a,b.c.d):
m-max(a,.b.c.d)

n=min(a.b.c.d)
Satbtctd

Fn.m,s)
return t

tl=change(2.5,7,20)
print (tl)
g.hi=t
print(g.h.i)
OUTPUT
(2, 20, 34)
2 20 34
12. Explain docstrings in python functions
ns. Another essential aspect of writing funetions in Python: docstrings. Docstrings describe what your function
Such as the computations it performs or its return values. These descriptions serve as documentation for
function so that anyone who reads your function's doestring understands what your function does, without hay
to trace through all the code in the function definition
after
the tunci Piacec
line
immediate

in
the
are placed
runction docstrings
quotation marks.
def change(x):
"check call by value
x-[7
print(x)
print(change doc_
a-[52.3,1]
changefa)
print(a)
OUTPUT
check call by value
(71
[5.2.3. 1]j OUTPUT: FUNCTIONS

9
1. Give the output
i) print("hi") 3. def sum(a,b):
def abc():
print("sum is ",at+b)
print("hello")
x=5
print("bye") y=10
abc() sum(x,y)
(i) def abc(): sum(20,40)
print("hello") Ans. Output:
print("hi) sum is 15
print("bye") sum is 60
abc()
(iii) print("hi") 4. Give the output of the
print("bye") def check(a):
following program
def abc():
for i in range(len(a)):
print("hello")
abc() a[il-a[ij+5
Ans. OUTPUT
return a

(i).(ii),ii) b-[1,2,3,4])
Ccheck(b)
bye print(c)
hello Ans. OUTPUT
2. def cal(): 6, 7, 8, 9]
i = 9 [21 (SP 16] 5. Give the
while i> 1: def sum(*a):
output
if 1%2=0:
x = i%2
s=0
i = i-1
tor i in a:
else: SSti
i = i-2 print(s)
sum(2,3)
print (x**2) sum(2,6,3)
Ans. 49
cal()
Ans. OUTPUTsum(1,2,3,4)
25 5
11
10
12
OUTPUT: DEFAULT PARAMETER
6. def calc(u):
2000 # 200.0
ifuo2-0:
return ut 10; 100.0 S 200.0

else 1000.0 # 100.0

return u+2; 100.0 S 200.0

def patterm(M.B-2): 9. Find and write the output of the following pythor
for CNT program code:
in
range(0,B):
printt cale(CNT),M.end) def Revert( Num.Last-2):
print) if Lasto2--0:
patten(***") Last-Last+ 1
pattern"#,4) else:
pattern"(a3) Last-Last-1

ns. OUTPUT for C in range(1,Last 1):


0 *3 * Num+-C
10 #3 #12 #5 # print(Num)
10 (3 a 12 (a A.B-20,4
Revert( A,B)
7. def Execute(M): B-B-1
if M%30: Revert( B)
retum M*3 Ans. 35
clse 9
return M 10:
10. Find and write the output of the following pyti
def Output(B 2)
code 3 120
for T in range (0,B)
def Convert( X 45.Y-30)
print(Execute(T)."*".end X-X-Y
print) Y-X-Y
Output(4) print (X."&"Y)
Output) returm X
Output( 3 )
A-250
ns. 0 *11 *12 *9 B-150
0 11 A Convert(A.B)
0*11 *12 print (A."&".B)
8. Find and write the output of the following Python BConvert( B)
code 3 comptt 191 print (A."&"B)
A Convert( A)
def Alter(P=15.Q-10)
P-PQ print (A."&",B)
Ans. 400 & 250
-PQ
400 & 150
print (P"#".Q)
retum Q 180 & 150
A 100 400 & 180
430 & 400
B-200
A Alter( A.B) 430 & 180

print (A."S".B) 11. Find and wnte the output of the following
code
B-Alter B) def
print (A,"S",B) Changert P.Q=10
A Alter( A) P PQ
print (A,"S"B) QP
ns. 20000 # 100.0 print (P"#" Q)
100.0 S 200 Tetun P
randint
1s.
randint(x.y) will return a value >= y. It will
x and <=
randrange(x.y) will return a value>x and <y.T
generate a random number from the inclusive range stop, step) doesn't include the stop number whileg
integer, i.e., it is exclusive.
This function takes two
parameters. Both are
mandatory. This function takes three parameters(start,stop.s
The randint (start, stop) includes both
start and
while generating random stop numbers parameters, two
integer parameters are optional. 1.e..
the optional
parameters. The default value o
For example,
random.randint(0, 100) will specified. The default value of the step 18
number between 0 to return any
100(both inclusive) random
What are the
random.randrange(0, 100) will Tc
return any =

alues that canpossible


between 0 to 99.
be outcome(s) executed from such as 0. 1, 2, ...99. It
nport random assigned to variable the
following
wing code? Also
NUMBER. Also specify the maximum
TRING="CBSEONLINE" speciuy
UMBER=r
=9
andom.randi
aile STRING[N]="L":
nt(0,3)
print
(STRING[N]
NUMBERNUMBER+1+STRING.NUMBER1
N=N-1
ES#NF#to + -
VALUES[10,20,30,40,50,60,70,80]:
the To
LAST.
i m p o r t r a n d o m

LAST =random.randint(BEGIN,4)
BEGIN-random.randint(1.3

LAST+):
(ii) 30 -
40 50 - 60
for
prnt

I i n range(
BEGIN,
(VALUES[I), "-".end=*"")

20 -
30
-
40 -

iw3
(ii)
10 -
50
)
30- 40
BEGIN:1
Ans. (i) 30-40-50-

value
for s
sccr
reee
enn at the
a t the time Of
of exen.

eachecution
on
on
M i n i m u m

LAST:1| displayed assiono


for an be
be assigne
to be
of the s.
value that can
Minimum
expected values

outputs(s)
are

the
m a x i m u m

v
possible specify
28. What code?
Also

the following

TO
import random

AR=[20.30,40,50.60,70]:
FROM=random.randint(1,3)

T O - r a n d o m . r a n d i n t ( 2 , 4 )

TO+1):
range(FROM,
for K in (iii) 50#60#70#
print (AR[K],
end="# *")
ii) 30#40#50#
(iv) 4
(i) 10#40#70# is 3,4
Maximum value FROM,TO
30#40#50#
Ans. (ii) OUTPUT: STRING

and print (x)


Python code carefully
29. Observe the following on the screen Findoutput()
which will appear
obtain the output, Ans. EAl1
of it.
SP 171
after execution
30. Give the output if input is "Hell
def Findoutput():
L="earn" a=input("*enter string")
X=" S

count=l1 for i in a:
for i in L: if i.islower():
ifi in['a','e',i','o','u']: s=s+(i.upper())
x=Xt1.swapcase() elif i.isupper():
else S=S+(i.lower))
if count%21=0: elif i.isnumeric():
x=X+str(len(L[:count])) S=s+str(int(i)+1)
else: else:
CountcOunt +1 S s + * »
dela) Val int(Text1[1})
Val =Val +1
prntnew value of str",a) Text2=Text2 + str( Val)
new value of str
s.
hELL*234 elif Text[]>="A" and Text1{I]="Z":
ord(): The ord) function returns the number Text2-Text2 + (Text1 [I+1])
representing the unicode code of a specified character else:
For example ord('B') returns 66 which is a unicode Text2=Text2 +
code point value of character 'B°'.
A-Z 65-90 +1
d-z 97-122 print (Text2)
chr): The chr()
function in Ans. ISSCE *3129
which is a unicode code Python accepts
an integer
point and converts it into a 34. Find and write the output of the following pP
strng representing a character.
code:
1. Find and write the
output of the Msgl="WelLcOME
code following Python
121 Icomptt 191 Msg2-"GUeSTs'
Str1="EXAM2018 Msg3-
Str2=*
for I in range(0,len(Msg2)+1):
if Msgl[I]>='A' and Msg1[I]<="M":
while 1en(Str1): Msg3=Msg3+Msg1[I
if Str[]>="A" and Strl[]<="M": elif Msg1[]>='N° and Msgl[I]<='Z°:
Str2-Str2+Strl[I+1] Msg3-Msg3+Msg2[
elif Str1[I]>="0" and Str1[|]<=*9": else
Str2-Str2+ (Str![l-1]) Msg3=Msg3+"**
else: print (Msg3)
Str2-Str2+***"
Ans. G*L*TME
35. Give the output
print (Str2)
s. X*M2M201 Text-"Mind@Work!
T=**
2. Give the output c=0
def makenew(mystr): for i in Text:
newstr=
if not i.isalpha():
count = 0
T=T+**
for i in mystr: elif not i.isupper():
if count%2!=0:
T-T+(Text[c+1])
newstr= newstrtstr(count) else:
elif i.islower(): T=T+i.upper()
newstr=newstrti.upper() c=c+1

else print(T)
newstr=newstr+i
Ans. Mnd@*Wrk!*
countt=1
newstr = newstrtmystr[:1]
36. Give the output

print (The new string is:",newstr) ext="Mind@Work!"


T-
makenew("sTUdeNT")
c=0
s. The new string is: SiU3ESTs
for i in Text:
3. Find and write the output of the following python if not i.isalpha():
code: 21 12019 T=T+**
Text1="AISSCE 2018"
elif not i.isupper():
Text2-
T=T+(Text[c+1])
else:
while I<len(Text1): vaFord(i)
if Text1 [I]>="0" and Textl[|]<="9":|
val val+1 =Msglilk"H"
M=M+Msg[i
T-T+chr( val) elif Msg[il"A
or
print( T)

Ans. Nnda *Xrk!*


M=M+C;
elif i%2-=0: Mseil-
else M-M+Msgli|.upper(
Mystring="Whata OUTPUT!"

M-M+Msg[i-1]
Str**

for i in range(len(Mystring)
if not Mystringi].isalpha(): print("New Line =

",M)
str-str+"** text-"ApaCHeSeRvE
elif Mystringli].isupper(): Mycode(text,"#*")
val-ord(Mystringli}) Ans. New Line =#A#chHS ReE
val-val+I1 41. Find the output of the follo
str=strtchr(val)
else: def Encode(Info,N):
In="*
fol owing pTOg
str=str+Mystringli+1
print(str) for I in range(len(Info):
Ans. Xat@*PVUQVU* if 1%2-0:
38. Give the output of the following program segment v=ord(Info[I])
NAME = "IntRAneT" V=v-N
N=
for x in range(len(NAME)):
In=Intchr(v)
elif Info[].islower()
if NAMEx].islower(0:
N=N+NAME[x].upper)
elif NAME[x].isupper():
else:
In=In+Info[|].upper(0
if x%2==0: vord(Info[I])
v=v+N
N=N+NAME[x].lower(0
else:
N=
In=In+chr(v)
N+NAME[x 1] -

print(ln)
print(N) Memo="Justnow"
Ans. iNTtaNEe
39. Find the
Encode(Memo,2)
output of the following program Ans. HUqTIOu
def Changelt(Text,C):
T- 42. Find the
output of the following program (t
for K in def Convert(Str,L):
range(len(Text):
if Text[K}>=F' and S=
Text[K]<="L':
elif T-T+Text[K]lower(): for Count in
range(len(Str):
Text[K)=E Text[K]=='e':or if Str [Count].isupper():
T=T+C;
elif K%2==0:
S=S+Str[Count].lower()
elif Str [Count].islower():
T-T+Text[K]upper()
else:
T=T+T[K-1] elif S-S+Str[Count).upper()
Str
print("New TEXT:",TI) [Count].isdigit
0 +l)
S=S+str(int(Str[Count])
OlChangel
dTextt=(Ol"pOwERALone" else:
Ans. New TEXT: dText,"%") S=S+*»
40. Find the PPw%RRIN% print(S)
output of the Text= "CBSE
def Mycode(Msg,.C): following program Exam 2021"
Size=len(Text)
Convert(Text,Size);
Ans. cbse*eXAM*3132
43. Find the output of the following program Name=N
def Change(Msg.L):
print(Name)
M=**
Ans. AOROolLE
for Count in [21 ISP 2019-201
range(0,L,1 ): 46. Give the output
if Msg [Count].isupper (): def fun(s):
M=M+Msg[Count].lower)
elif Msg[Count].islower():
k=len(s)
M- M+Msg[Count).upper()
for i in range(0,k):
elif Msg [Count].isdigit():
if(s[i].isupper():
C=int(Msg[Count])
C-C+1
m=mts[i].lower()
elif s[i].isalpha():
M-M+str(C) m-m+s[i].upper()
else:
M= M+°*»
else:
m=m+°bb
print(M)
Message = *2005 Tests ahead" print(m)
Size=lenMessage) fun('schoo12@com)
Ans. SCHOOLbbbbCOM
Change(Message,Size)
ns. 3116*tESTS*AHEAD 47. Give the output
44. Find the output of the def repch(s):
def Secret(Msg.N):
following program: p > * »

Mg= for i in range(len(s)-1):


for c in if i%2!=0 and s[il-=s[i+1]:
range(len(Msg)): pp+"@
if c%2-=0:
vord(Msg[c]) print("Hello")
elif s[il- =s[i+1]:
v=v+N
pp+"!
Mg-Mgtchr(v) else:
elif Msg[c].isupper(0:
Mg Mg+Msg[c].lower() pptsi]
else: print(Changed String".p)
str "SUCCESS"
Vord(Msg[c])
V=y-N print(Original String",str)
repch(str);
Mg-Mgtchr(v) Ans. Original String SUCCESS
print(Mg) Hello
SMS = "rEPorTmE"

Secret(SMS,2) Changed String SU!CE@


48. Find the output of
teRmttoe the following program
def MIXITNOW(S):
Give the output of the following program WS=*
Name="a ProFile"
for I in
= range(0,len(S)-1,2):
or x in range(0,len(Name), 1): WS-WS+S[+1]
if Name[x].islower(): WS-WS+S[I]
S=WS
N-N+Name[x].upper(0 print(S)
elif Name[x].isupper():
WS-
if x%21=0:
for I in range(0,len(S):
N=N+Name[x-1].lower() if S[>="M" and
else: S[I]k="U":
n-ord(Name[x}) WS-WS+"@"
else:
n=n-l

N=N+chr(n)
WS-WS+S[1-1:]
print(WS)
Ans. AHMRI

AH@@O1@
Word-"CRACKAJACK":
50. Find the output of the
Ans.
MIXITNOW(Word):
RCCAAKAJKC
def Big(A,B):
if (A>B):
following
@RCCAAKAJK
program return chr(ord(A)+1
9 Find the output of the following else:
def JumbleUp(T):
CT=*
return chr(ord(B)+2
WX="Exam"
L=len(T)
W=3
for C in range(0,L,2):
CT-CT+T[C+1] L=len(WX)
CT-CT+T[C] for i in range(0,L-1,1):
T-CT
CT=* W=W+Big(WX[1].WX[i+
W-W+Wx[L-1]
print(T)
print(W)
for C in range(1,len(T),2):
and Ans. zyom
if "U>=T[C]>="M": #if T[C]>="M"
T[C]="U": 51. Give the output
CT-CT+"@" a-"Hello"
else L=list(a)
CT-CT+T[C-1:C+1]
print(CT) ajoin(reversed(L))
Str-"HARMONIOUS" print(a)
Ans. olleH
JumbleUp(Str)
OUTPUT: GLOBAL VARIABLE
52. What do
you understand by local and global scope 54. a-5
of variables? How can
you access a global variable def fun(O:
inside the function, if function has a
variable with
same name. a-10
Ans. A SP 2019-20]
global variable is a variable that is accessiblee print(a)
globally. A local variable is one that is only accessible fun()
to the current
scope, such as
temporary variables print(a)
used in a single function
A variable declared
definition. Ans. 10
outside of the function in 5
global is
scope known as
global variable.
or

This means, 55. a-5


global variable can be accessed
or outside of the function where inside def fun():
as local
be used only inside of the variable can
by declaring variable as function. We can access global a
Note: In case global A. a=10
you have a local
same name, use
the variable with the print(a)
global variable. globals() function to access fun()
globals)['your_global_var']
for ex: print(a)
Ans. 10
yglobals(O['a']
Give the output 10
53. a-5 56. a-5
def fun():
def fun(a):
print(a)
fun() a=10
printa)
Ans. 5 print(a)
5
fun(a)
print(a)
Ans. 10
57. a5 func(g.h)
det tun) printg.h)
global a
a 10
tuncg
prnt( g.h)
Ans. -3 10 50
prnt nside".a)
print'y 10
fun) 52 50
pnntoutside".a) 7 10
ns. insde 10
10
62. g-10
outside 10 de func(x.y=10):
X-y
58. a-5
y-x*10
det tun):
ZX*ytg
a-10
return z
func(g.15)
print("inside".a)
print(g)
print-".y)
fun) func(g)
print"outside".a) print(g)
ns. inside 10 Ans. -45
-10 -650
outside 5
63. a-3
59. Find and write the output of the def demo(x.y):
following python global a
code:
ISP 2019-201
a-10 a-Nty
def call) Zaty
global a yt=x
a=15 print(x,y.z)
b-5
b-20
print(a)
demo(a.b)
print(a.b)
call)
ns. 15
demo(a.b)
Ans. 3 8 13
60. a=5 85
def fun): 8 13 18
a=10
64. def pa(a.b.c):
globalsO[a'] x=4
print("inside".a)
et=x
print("y=",y)
fun)
c globals(O['x°']
bt=c
print("outside".a)
return a,b.e
ns. inside 10
5
y=l
x-2
outside 5
Z=5
61. def func(x.y=2):
X,y.z=pa(y.x,z)
g-5
print(x.y.z)
X=X-y y,Z,X=pa(Z,y.x)
gg10:
print(x.y.z)
print(x.y.g) Ans. 1 20 18
g-7
h=10 5 18 25
FUNCTIONS/METHOD.
Description
e q u a l to x.
than or
greare
Math Module integer
smallest x
value of
Function Returns
the
absolute
the
ceil(x) Returns
factorial ofx less
than or equal to X
the
fabs(x) Returns
the largest
integer
IS
divided by y
X
factorialx) Returns

remainder
when

Hoortx) Returns
the
NaN
if x is
a
fimod(x. y) True value
of x
Returns
integer
truncated

ISnan(x) the
Returns
trunc(x) Returns e**x
of x
logarithm
base-10
exp(x) Returns
the
power y
| log10(x) raised to the
Returns X
ofX
pow(x. y) Returns the square
root

sqrt(x) cosine of x
Returns the
cos(x) sine of x
Returns the
sin(x) of x
Returns the tangent
tan(x) radians to degrees
x firom
Converts angle of a circle to it's
degrees(x) Mathematical constant, the ratio or circumterence diameter (3.i
pl constant e (2.71828...
e
mathematical
Csv module Pickle module
Random module
dump) load) Dictreadwe) DictWriter(
randint()random() randrange() unitorm() eade
Statistics module
Matplotlib.pyplot
axes) bar) bath) plot) pie) mean() median
show() title) xlabel() ylabel() mean) median mo
65. Name the Python Library modules which need to be imported to invoke the followi
iceil() (ii) randint() Ing i
Ans (i) math (ii) random
66.
Observe the following Python functions and write the name(s) of the module(s) to which thev beloma.
(b) findalI)
Ans. (a) random (b) re
67. Name the Python Library modules which need to be imported to invoke the
(ii) randint() following functions (
Ans. (i) math (ii) random
68. Identify and write the name
Ans. (i) ceil() math module (1i)
of the module to which the
following functions belong: (i) ceil() (i)
findall
-

findall( ) - re module
69. Name the
Python Library modules which need
(ii) pow() to be imported to
Ans.
invoke the following functions
(i) pickle (ii) math
70. Name the
Python Library modules which
(i) dump(0 need to be
Ans. (i) math
(ii) pickle
imported to invoke the following Tue
inctions=

71. Name the


(1i) search()
Python Library modules
which need to be
Ans. (i) math
(ii) re imported to invoke the followinng functions
72. Name the
ii) gives the function/on/method required
total length to
Ans. (1) of the list. (i) check if
isupper() (ii) len() a
string
String contains only upperea
73. Name the function/method required to (i) check if (ii) give the total length
the list.
a string contains only alphabets o
ns. Isalpha() |OD 15
len()
74. the
Name Python Library modules which need to be imported to invoke the following functions: (1)
(i) factorial() Open
ns. (1) os (ii) math 1 lcomptt 2019|

.Name the Python


Library modules which need to be imported to invoke the following functions
(ii) date() (1) Scarc
ns. (1) re (ii) datetime 1 |2019

0.
Name the Python Library modules which need to be imported to invoke the following functions (1) Sqrtt
(ii) start ()
ns. (i) math (ii) re [1 [2019

ERRORSs
Rewte the
tollowing Python program after removing all the syntactical (if
correction.: errors
any),underlining eac
2] ISP 16
def checkval:
x =

input("Enter number")
a
if x % 2 0
print x, is even"
else if x<0:
print x,"'should be positive"
else;
print x,"is odd"
ns. def checkval():
x
int(input("Enter a number"))
ifx % 2 ==0
print (x, is even'")
elif x<0
print (x,"should be positive")
else
print (x,"is odd")
2. Rewrite the following code in python after removing all
code.
syntax error(s). Underline each correction done in
def Tot(Number) #Method to find Total 2 [D
Sum-0
for C in Range (1, Number+ 1):
Sumt=C
RETURN Sum
print Tot[3] #Function Calls
print Tot[6]
ns. def Tot(Number)
Sum-0
for C in range (1, Number+1):
Sumt-C
return Sum
print (Tot(3))
print (Tot(6))
3. Rewrite the following code in python after removing all syntax error(s). Underline each correction done
code 21 10
def Sum(Count) #Method to find sum
1.Count+1):

S-0
Range(
for I in
S+I
RETURN S Call
#Function

Sum[2]
print sum
find
print Sum[5] #Method
to
Sum(Count):

Ans.
def
S-0 range(1.Count+1):

for I in

S+l
return S #Function
Call
(Sum(2)
print
syntactical
errors (if
(if any). Underline
print (Sum(5) the
removing
code ater
. Rewrite the following
def chksum:
xInt(input("Enter
a number )
if (x°%2 = 0)

for i range(2*x):
print (i)
else
print ("#")
Ans. def chksum():
x= int(input("Enter a number")
if x%2 == 0:
for i in range(2*x):
print (i)
else:
print (")
5. Observe the
following Python code very carefully and rewrite it atter
corection underlined. removing all sn
DEF execmain():
X=input("Enter a number")
Ifabs(x)=x):
Print'you entered a
positive number"
else:
x=*-1
print "Number made
execmain(0 positive:"x
Ans. def execmain():

Xint(input("Enter anumber"))
if abs(x)=Ex:

else: print("you entered a


positive number")
x*=-1
execmain()0 print ("Number made
6.
Rewrite the positive:".x)
Code. following code in
"HELLO-String Python after
for I in removing all syntax
range(0,len(String)-1) error(s).
error(s). Underline cat
if String[]=>"M":
print String[1],"**
Ise
print String[l-1]
tring"HELLO"
or I in range(0,len(String)-1):
if String[I>="M":
print (String[|],"*")
else:
print (String[1-1)
the tolowing code in python after removing all syntax error(s). Underline each
correction done n
cwte
ode.
D 16
or Name in [Amar, Shveta, Parag]
IF Name[0]="S:
print(Name)
or Name in Amar", Shveta", *Parag":
if Name[0]= =S°:
print(Name)
ewrite the following code in python after removing all syntax error(s). Underline each correction done in tne
ode. 2] [OD 16]
or Name in [Ramesh,Suraj,Priya]
IF Name[0]-"S
print(Name)
or Name in ["Ramesh""Suraj","Priya"]:
if Name[0]=='S°:
print(Name)
DEFINITION FUNCTION(DICTIONARY)
Vrite a user defined function findname(name) where name is an argument in Python to delete phone number from
dictionary phonebook on the basis of the name ,where name is the key. 21 (SP 161
ef findname(name):
f phonebook.has_key0:
del phonebookfname]
lse:
print"Name not found"
print "Phonebook Information"
print "Name",'\t","Phone number"
for i in phonebook.keys):
print i,'r',phonebook[i]
DEFINITION FUNCTION
Vrite a python method/function REVERSAR (Number) to find a new number Reverse from Number with each
f the digits of Number in reversed order and display the content of Reverse on screen.
comptt 17
or Example:
f the value of Number is 3451
he method/function should be displayed as 1543
21 [201
ief REVERSAR(Number):
S=0
while Number>0:
S-S*10+Number%10
Number- Number//10
print(S)
REVERSAR(Number)
Number str(Number) betwee.
en
numbers
2 to
the
composite
N.
print( Number|::-1))
find and display Pass N
a method in pvthon to
Wrie
method.
Ans. def composite numbers(N):
for I in range(2, N):
M 1/2
M+1):
tor J in range(2,
if I % J
==
0:
print(1)
break
the prime
numbers between 2 to Ar

Write a method in python to find and display


Pass Na
method.
Ans. def prime(N):
for a in range(2,N):
for i in range(2,a):
ifa%i=0:
break
else:
print (a)
4. Write a
Python method/function Count(Start, End,Step) to display natural numbers from S
intervals of Step art t
For example
If the values of Start as
14, End as 35 and Step as 6
The method should be
14 displayed as

20
26
32
Ans. def
Count(Start,
for i
End, Step):
in
print(i)
range(Start, End, Step):
5. Write a
python
between 1 and N,method/ function
For Example:
which are either Count3and7(N)
divisible
to find
and display
by 3 or the count of all those unt
If the value of N is by 7. nu
15
The sum should
be
(as displayed as 7
3,6,7,9,12,14,15
Ans. def Count3and7(N): in between 1 to
l5 are
c=0 either divisible by
for i in 3 or 7)
range(1,N+1):
if i%3=0
or
CC+1 i%7-0:
print (c)
Count3and7(15)

You might also like