Python HandsOn-Function&OOPs
Python HandsOn-Function&OOPs
word1 = ''
newpara = ''
for i in para:
if i in special1:
newpara += i
else:
word1 += i
rword2 = word1[:70]
rword2 = rword2[::-1]
print(rword2)
flag = 0
for each in list1:
if each in para:
continue
else:
flag = 1
break
if flag:
print("Every string in {0} were not present".fo
rmat(list1))
else:
print("Every string in {0} were present".format
(list1))
splitted = word1.split()
print(splitted[:20])
ans = []
for each in splitted:
if splitted.count(each) < 3:
if each not in ans:
ans.append(each)
print(ans[-20:])
print(word1.rindex(strfind))
lst = []
for i in range(3,n1+1):
M = i*(i*i + 1)/2
lst.append(M)
for i in range(len(lst)):
yield lst[i]
Prime Number Generator:
def primegenerator(num, val):
# Write your code here
lst = []
lst1 = []
lst2 = []
odd=1
even=0
for i in range(len(lst)):
if(i % 2 == 0):
lst1.append(lst[i])
even += 2
else:
lst2.append(lst[i])
odd +=2
if(val):
for i in range(len(lst1)):
yield lst1[i]
else:
for i in range(len(lst2)):
yield lst2[i]
Classes and Objects 1:
Task 1:
# Write your code here
class Movie:
def __init__(self,name,n,cost):
self.name = name
self.n = n
self.cost = cost
def __str__(self):
return"Movie : {self.name}\nNumber of Tickets : {sel
f.n}\nTotal Cost : {self.cost}".format(self=self)
Task 2:
#Write your code here
class comp:
def __init__(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 __init__(self,t):
self.t = t
def display(self):
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
elf.t,2)))
class daughter(parent):
def __init__(self, t, dp):
self.dp = dp
parent.__init__(self,t)
def daughter_display(self):
Percentage_for_daughter = (self.t*self.dp)/100
print("Share of Daughter is {} Million.".format(round(P
ercentage_for_daughter,2)))
print("Total Asset Worth is {} Million.".format(round(s
elf.t,2)))
Task 2:
# Write your code here
class rectangle:
def display(self):
print("This is a Rectangle")
class square:
def display(self):
print("This is 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):
# Write your code here
l = []
if val == 1:
c1 = datetime.date(tup[0],tup[1],tup[2])
l.append(c1)
l.append(c1.strftime("%d")+"/"+c1.strftime("%m")+"/"
+c1.strftime("%Y"))
elif val == 2:
c1 = datetime.date.fromtimestamp(tup[0])
l.append(c1)
elif val == 3:
c1 = datetime.time(tup[0],tup[1],tup[2])
l.append(c1)
l.append(c1.strftime("%I"))
elif val == 4:
c1 = datetime.date(tup[0],tup[1],tup[2])
l.append(c1.strftime("%A"))
l.append(c1.strftime("%B"))
l.append(c1.strftime("%j"))
elif val == 5:
c1 = datetime.datetime(tup[0],tup[1],tup[2],tup[3],t
up[4],tup[5])
l.append(c1)
return l
Modules 2: Itertools
import itertools
import operator
def performIterator(tuplevalues):
# Write your code here
l1 = []
ans = []
temp = itertools.cycle(tuplevalues[0])
count = 0
for i in temp:
l1.append(i)
count+=1
if count == 4:
break
ans.append(tuple(l1))
ans.append(tuple(list(itertools.repeat(tuplevalues[1][0],le
n(tuplevalues[1])))))
temp = itertools.chain(tuplevalues[0],tuplevalues[1],tuplev
alues[2],tuplevalues[3])
ans.append(tuple(list(temp)))
tempForTask5 = list(itertools.chain(tuplevalues[0],tupleval
ues[1],tuplevalues[2],tuplevalues[3]))
return tuple(ans)
Modules 3: Cryptography
from cryptography.fernet import Fernet
def encrdecr(keyval, textencr, textdecr):
# Write your code here
mainList = []
f = Fernet(keyval)
mainList.append(f.encrypt(textencr))
d = f.decrypt(textdecr)
mainList.append(d.decode())
return mainList
Modules 4: Calendar
import calendar
import datetime
def checkLeapYear(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return 1
else:
return 0
else:
return 1
else:
return 0
def usingcalendar(datetuple):
year = datetuple[0]
leap = checkLeapYear(year)
if leap == 1:
month = 2
else:
month = datetuple[1]
print(calendar.month(year,month))
#--------------------------------------
m = calendar.monthcalendar(year, month)
mondays = [week[0] for week in m if week[0]>0]
day = mondays[-1]
lst = []
MONTH = month
YEAR = year
for i in range(7):
d = datetime.date(year,month,day)
lst.append(d)
day = day + 1
print(lst)
#------------------------------------------------------------
----------
a = (datetime.datetime(YEAR,MONTH,1))
starting_day = a.strftime("%A")
print(days[pos])
Modules 5: Collections
import collections
def collectionfunc(text1, dictionary1, key1, val1, deduct, l
ist1):
# Write your code here
d = {}
for each in text1.split():
if each in d:
d[each] += 1
else:
d[each] = 1
sort_d = dict(sorted(d.items(), key = lambda kv:kv[0]))
print(sort_d)
cou = collections.Counter(dictionary1)
for each in deduct:
cou[each] -= deduct[each]
print(dict(cou))
orde = collections.OrderedDict()
for i in range(len(key1)):
orde[key1[i]] = val1[i]
del orde[key1[1]]
orde[key1[1]] = val1[1]
print(dict(orde))
d4 = {"odd":[], "even":[]}
for i in list1:
if i%2==0:
temp = d4["even"]
temp.append(i)
d4["even"] = temp
else:
temp = d4["odd"]
temp.append(i)
d4["odd"] = temp
if d4["even"] == []:
del d4["even"]
if d4["odd"] == []:
del d4["odd"]
print(d4)
Handling Exceptions 1:
def Handle_Exc1():
# Write your code here
a = int(input())
b = int(input())
if(a>150 or b<100):
print("Input integers value out of range.");
elif(a + b) > 400:
print("Their sum is out of range")
else:
print("All in range")
Exceptions 2:
def FORLoop():
# Write your code here
n = int(input())
l1 = []
for i in range(n):
l1.append(int(input()))
print(l1)
iter1 = iter(l1)
for i in range(len(l1)):
print(next(iter1))
return iter1
Handling Exceptions 3:
def Bank_ATM(balance,choice,amount):
# Write your code here
flag = 0
if balance < 500:
print("As per the Minimum Balance Policy, Balance mu
st be at least 500")
else:
if(choice == 1):
if amount < 2000:
print("The Minimum amount of Deposit should
be 2000.")
else:
flag = 1
balance += amount
if(choice == 2):
if(balance - amount)<500:
print("You cannot withdraw this amount due t
o Minimum Balance Policy")
else:
flag = 1
balance -= amount
if(flag):
print("Updated Balance Amount: {}".format(balance))
Handling Exceptions 4:
def Library(memberfee,installment,book):
# Write your code here
if(installment > 3):
print("Maximum Permitted Number of Installments is 3")
else:
if (installment == 0):
print("Number of Installments cannot be Zero.")
else:
print("Amount per Installment is {}".format(member
fee/installment))
book = book.lower()
if book in ListOfBooks:
print("It is available in this section")
else:
print("No such book exists in this section")