Functions Assignment
Functions Assignment
2 that is
used to
perform
reusing.
a single, related action. Functions.
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-
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
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
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
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
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 =
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
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
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
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 > * »
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
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=
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:
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)