0% found this document useful (0 votes)
769 views15 pages

Python Hands On Answers

This document contains code snippets related to various Python concepts: 1. The first section contains a method that performs string operations like extracting words and replacing spaces. 2. The second section defines a generator function to generate magic constants. 3. The third section defines a prime number generator function that yields prime numbers. 4. Further sections contain code related to classes and objects, modules like datetime, itertools, cryptography etc. and exception handling.

Uploaded by

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

Python Hands On Answers

This document contains code snippets related to various Python concepts: 1. The first section contains a method that performs string operations like extracting words and replacing spaces. 2. The second section defines a generator function to generate magic constants. 3. The third section defines a prime number generator function that yields prime numbers. 4. Further sections contain code related to classes and objects, modules like datetime, itertools, cryptography etc. and exception handling.

Uploaded by

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

String Methods:

def stringmethod(para, speciall, special2, listl, strfind) :


P Nnit e youP c ode he r e

wordl = ' '


newpar'a —
fon i in para:
if i
speciall:
newpara += i
else:
word1 += i

rword2 = word1[:70]
rword2 = ruord2 [ : -: 1
print (ruord2

nospace = rwoFd2 . rep 1ace ( " " , '


nospace = s pecla12. j oin nospac e)
print nospac e)

flag = 0
for each in list1:
if each in para:
continue
else:
flag =
1 break

if flag:
pnint("Every string in (0} were not present”.fo
rmat(1ist1))
else:
pnint("Every string in (0) were present”.fonmat
(list1))

splitted = word1.split()
print(splitted[:2g])
ans []
for each in splitted:
iT splitzed.cOunt(each) <
if each nOt in ans:
ans.append(each)

print(ans[ :])

p n i n t (nond 1 . n i nde x(s t nfi nd ) )

Magic Constant Generator:


def generazor_Magic(n1):

lst []
for i in range( ,n1+ ):

Isz . append (M)

for i in range(len(lst)):
yield 1st[i]
Prime Number Generator:
del pr1megenen afar (num, va1) :

lst
lstl []
lst2 []
odd=
even-

for i in range( , num+ ):

for j in range( ,i}:

D sea k ;

1st . append ( 1)

for i in
range(len(1st)):
of(i % ):
lstl.append(1st[i])
even +=
else:
lst2.append(lsz[i])
odd +=

iT(val):
for i in range(len(lscl)):
yield lsz1[i]
else:
for i in range(len(lsi2)):
yield lsz2[i]
Classes and Objects 1:
Task 1:
# Write your code here
class Movie:
def finite(self,name,n,cost):
self.name = name
self.n n
self.cost = cost
def Astra(self):
return”Movie : {self.name}\nNumber of Tickets : {sel
f.n}\nTozal Cost : {self.cost}”.format(self=self)

Task 2:
#Write your code here
class comp:
def finite(self, a,b):
self.a a
self.b b

def add(self,other):
print(”Sum of the two Complex numbers :{}+(}i”.forma
t(self.a + other.a, self.b + other.b))

def sub(self,other):
if(self.b>=other.b):
print("Subtraction of the two Complex numbers :(
}+{}i”.format(self.a - other.a, self.b - other.b))
else:
print("Subtraction of the two Complex numbers :(
}{}i”.format(self.a - other.a, self.b - other.b))
Classes and Objects 2:
Task 1:
#Write your code here
class parent:
def finite(self,t):
self.t = t
def display(self):

print(”snare of Parents is {} MilliOn.”.format(round((s


elf.t)/2,2)))

class son(parent):
def init (self, t, sp):
self.sp = sp
parent. init (self,t)

def son_display(self):
Percentage_for_son = (self.t*self.sp)/100
print("Share of Son is {} Million.”.format(round(Percen
tage_for_son,2)))
print("Total Asset Worth is (} Million.".format(round(s

class daughter(parent):
def finite(self, t, dp):
self.dp = dp
parent.finite(self,t)

def daughter_display(self):
Percentage_for_daughter = (self.t*self.dp)/100
print(”Snare of Daughter is (} Million.".format(round(P
ercentage_for_daught er, 2)))
print(”Total Asset Worth is () Million. ”.format(round(s
elf.t,2)))
Task 2:
e Write your code here
class rectangle:

def display(self) :
pnint ( "Th i s is a RecI ang1e " )

def area(self, a, b):


self.a = a
self.b = b
print("Area of Rectangle is {}”.format(self.a * self.b))

class square:

del d1sp1ay ( sell) :


pnint ( "/h1s 1s a Square " )

def area(self,a):
Self.a a
print(”Area of square is {}”.format(self.a * self.a))
Modules 1: Date Time
import datetime
def dateandtime(val,tup):
9 T4rite your code here
l []
if val -= 1:
c1 - datet:1ne . date(tup[ ] , tup[1 ] , tup [ 2] )
1. append (c1)
1.append(c1.strftime(”%d”)+”/”+c1,strftime(”%+>”)+”/”
+c1.strftime(”%Y”))

elif cal == 2:
c1 = datetime.date.fromtimestamp(tup d])
l.append(Cl)

elif val == 3:
cl = datetime.time(tup[ tJ],
tup[i],tup[S]) l.append(c1}
l.append(c1.strftime(”%I”))

elif val == ::
c1 = datetime.date(tup[ ],tup _],tup[1])
l.append(c1.strftime("%A”))
1.append(cl.Strftime( ”%B”))
l.append(c1.strftime(”% j”))

elif val == 5:
c1 datetime.datetime(tup[ L], tup[l],tup[2],tup[3],t
up[%],tup[*])
l.append(c1)

return l
Modules 2: ltertools
import iterzools
import operator

def performIterator(tup levalues):


# Write your code here
11 []
ans = [ ]

temp itertools.cycle(tuplevalues[0

]) count = 0
for i in temp:
11.append(i)
count+- 1
if count == 4:
break
ans . append (tup1e(11) )

ans.append(tuple(list(itertools.repeat(tuplevalues[1][0],le
n(tupleva1ues{1])))))

temp itertools.accumulate(tuplevalues[2], operator.add)


ans.append(tuple(list(temp)))

temp = itertools.chain(tuplevalues[0],tuplevalues[1],tuplev
alues[2],tuplevalues[3])
ans.append(tuQle(list(temp)))

tempForTask5 = list(itertools.chain(tuplevalues[0],tupleval
ues[1],tuplevalues[2],tuplevalues[3]))

temp2 = itertools.filterfalse{lambda x:x%2==0,tempForTask5)


ans.append(tuple(list(temp2)))

return tuple(ans)
Modules 3: Cryptography
from cryptography.fernet import Fernet
def encrdecr(keyval, texzencr, zextdecr)
:

mainList = ]
f - Fernet(keyval)
mainList.append(f.encrypz(textencr})
d - f.decrypt(texzdecr)
mainList.append(d.decode())

return mainLisz

Modules 4: Calendar
inport calendar
oaport datetLmQ

del c he ckL exp Ye as (year) :


if (year % ) ==
if {year % )
if (year % )
== return
else:
return
else:
return
else:
return

def usingc a1endar(datetuple):


yea n = dat ed upI e [ ]

leap = chec I‹LeapYear (year')

if leap ==
else:
month = datetuple[ ]

pr1nt ( ca1enda r . nonth (year, mont h) )

m = calenaar . oonthca lendar (year, month )


Mondays = [week [ ] for week in a if week [ ›
day - nonaays [

MON TH =
month YEAR =
year

for i in range( ) :
d = datetime . date(year ,month, day)

\ st . a ppend ( d

if (leap == } and (month == ):


¿I (day == ):
day =
if (month
mont h =
year = year +
else:
month = month +

elif (leap == ) and (month == ):


if(day == ):
day =
if(month
month

else:
mont h = month +
else:

i I ( ( mont h == ) OP ( lTIOnt h == ) o
(mo nt h == ) r ( conth =- ) or
(mont h =- ) or (month- • oI°
(month == )) and (day == ):
day
if(month == tl):
lnontn = 1
year = year + 1
else:
= month + I

elif((month +) or (month 6) or (month ;)


or (month 11)) and (day %E):
day
if(month == i2):
month = 1
year = year + 1
else:
noneh = rronz h + 1

day = day + 1

print (lst)

a = (datetime.datetime(YEAR,MONTH,l))
szariing_day = a.strftime(”%A ”)

days = [ ”Monday”, ”Tuesday”, ”Wednesday”, ”Thursday ", ”Frid


ay”, ”Saturday ”, "Sunday” ]
couns= [:• for i in range(0,7)]
pos=-l
for i in range(0,*):
if (starting_day == days[i]):
pos = i
break

prim(days[pos])
Modules 5: Collections
import collections
def collectionfunc(text1, dictionaryl, keyl, vall, deduct, l
istl) :
4 Write your code here
d (}
for each in text1.split{):
if each in d:
d [ each 1 +-
else:
d[each ] 1
sort_d = d:Act ( sorted(d . Items ( ) , key = lambda kv: kv [3] ) )
pr'int ( sort_d )

cou = collections.Counter(dicTionaryl)
for each in deduct:
cou[each ] - = deduct [each]

print(dice (cou))

orde = collections.OrderedDicz ()
for i in range(len(keyl)):
orde[key1[i]] = Val1[i]

del orde keyl 1jj

orde key1[1jj = call 1]

print(dict(orde))

d4 - { " odd" : t 1. ” even " : 111


for i in
listl: if
i% ==0:
temp = d4["even
”]
temp.append(i)
d4[”even' ] -
temp
else:
temp = d4[”ood”j
temp.append(i)
d4[”odd”] = temp
if d4[”even”] == [] :
del d4[”even"j
if d4["odd”] == ]:
del d4[”odd”]
print(d4)

Handling Exceptions 1:
def Handle_Exc1():
# Write youn code he be
a = int(input())
b = int(input())

if (a › 1>6 or b‹ t6 0) :
print(”Input integers value oua of range.”);
elif(a + b) > 400:
print(”Their sum ls our of range”)
else:
print(”All in range”)
Exceptions 2:
def FORLoop ( ) :
S Write your code here
n = int(input())
l1 []
fOr i in range(n):
11.append(int(input()))

print(11)
iterl = iter(11)

fOr i in range(len(11)):
pr nt(next(iterl))

return iterl

Handling Exceptions 3:
def Bank_ATN(balance, cho1ce, amount ) :
o Write your code here
flag 0
if balance < 500:
print(”As oer she Minimum Balance Policy, Balance mu
si be at least SOO”)
else:
if(choice == ):
if amount < 2000:
print(”The Minimum amount of Deposit should
be 2000.")
else:
flag I
balance += amount
if(choice == 2):
if(balance - amount)<500:
print("You cannon withdraw this amount due z
o Minimum Balance Policy”)
else:
flag I
bslance -= amount

if(flag)
print(“Updated Balance Amount: {)”.format(balance))

Handling Exceptions 4:
def Library(memberfee,installment,book):
D Write your code hcre
if(installment > 3):
print(”Maximum Permitted Mumber of Installments is 3”)

else:
if (installment == O):
print(”Mumber of Installments rannot be Zero. ')
else:
print("Amount per Installment is (}”.format(member
fee/installment))

ListofBooks = ["philosophers stone",”chamber of sec


rets ', "prisoner Of azk3ban", "goblet of fire", ”order of phoen
ix”, "nalf blood price", ”deathly hollows l”, ”deathly wallows
2”]

book book.lower()
if book in ListofBooks:
print("It is available in this section”)
else:
print("No such book exists in this section")

You might also like