Python Func& Oops Handson
Python Func& Oops Handson
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 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")
Magic constant
def generator_Magic(n1):
# Write your code here
for i in range(3, n1+1):
gen1 = i * ((i**2) + 1) // 2
yield gen1
Primegenerator
def primegenerator(num, val):
# Write your code here
x = 0
for i in range(2,num):
if(len([j for j in range(2,i-1) if i%j==0]) == 0):
x = x + 1
if(int(val) == 0):
if (x % 2) == 0:
yield i
if(int(val) == 1):
if (x % 2) != 0:
yield i
Modules 2: Itertools
import itertools
import operator
def performIterator(tuplevalues):
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
], len(tuplevalues[1])))))
temp = itertools.accumulate (tuplevalues[2], operator.add)
ans.append (tuple(list (temp)))
temp = itertools.chain (tuplevalues[0], tuplevalues [1], tuplevalu
es[2], tuplevalues[3])
ans.append(tuple(list (temp)))
tempForTask5= list(itertools.chain (tuplevalues[0], tuplevalues [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, 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
class rectangle:
def display (self):
print("This is a Rectangle")
def area(self, a, b):
self.a = a
self.b = b
print("Area of Rectangle is {}".format(self.a * self.
b))
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 4 Calendar
import calendar
import datetime
from collections import Counter
def usingcalendar(datetuple):
# Write your code here
year=int(datetuple[0])
mon=datetuple[1]
if year % 4== 0 or year % 100 == 0 or year % 400 == 0:
mon=2
date=calendar.TextCalendar(calendar.MONDAY)
print(date.formatmonth(year,mon))
l = []
obj = calendar.Calendar()
for day in obj.itermonthdates(year, mon):
l.append(day)
rev = l[:-8:-1]
rev.reverse()
print(rev)
count=Counter(d.strftime('%A') for d in obj.itermonthdates(year
,mon) if
d.month==mon)
for i,j in count.most_common(1):
print(i)
Handling Exceptions 3
class MinimumDepositError(Exception):
pass
class MinimumBalanceError(Exception):
pass
def Bank_ATM(balance,choice,amount):
#print(balance)
#print(choice)
#print(amount)
if balance < 500:
raise(ValueError("As per the Minimum Balance Policy, Balance
must be at least 500"))
if choice == 1:
if amount < 2000:
raise(MinimumDepositError("The Minimum amount of Deposit
should be 2000."))
else:
balance+=amount
print("Updated Balance Amount: ",balance)
if choice == 2:
if balance-amount < 500:
raise(MinimumBalanceError("You cannot withdraw this am
ount due to Minimum Balance Policy"))
else:
balance-=amount
print("Updated Balance Amount: ",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 (memberfee
/installment))
ListOfBooks = ["philosophers stone", "chamber of secret
s", "prisoner of azkaban", "goblet of fire", "order of phoenix", "h
alf blood price", "deathly hallows 1", "deathly hallows 2"]
book = book. lower()
if book in ListOfBooks:
print("It is available in this section")
else:
print("No such book exists in this section")
Modules 5: Collections
import collections
def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):
# Write your code here
tmp = list()
mydict = dict()
li = list(text1.split(" "))
items = collections.Counter(li)
y = sorted(items.items())
fix = str(y).replace('[(', '{').replace(')]',
'}').replace('\',','\':').replace('), (',', ')
print(fix)
items = collections.Counter(dictionary1)
res1 = {key: items[key] - deduct.get(key, 0) for key in items.k
eys()}
res2 = {key: items[key] - deduct.get(key, 0) for key in deduct.
keys()}
res = {**res1, **res2}
print(res)
keyval = dict(zip(key1, val1))
count = int()
for k,v in keyval.items():
count += 1
if count == 2:
keyval.pop(k)
break
keyval.update([(k, v)])
print(keyval)
even=list()
odd=list()
for i in list1:
if (i % 2) == 0:
even.append(i)
else:
odd.append(i)
oedict = {}
if len(odd) > 0 and len(even) > 0:
print("{'odd': " + str(odd) + ", 'even': " + str(even) + "}
")
elif len(odd) == 0 and len(even) > 0:
print("{'even': " + str(even) + "}")
elif len(odd) > 0 and len(even) == 0:
print("{'odd': " + str(odd) + "}")
else:
print(oedict)
def stringmethod(para, special1, special2, list1, strfind):
for myChar in special1:
para = para.replace(myChar,"")
word1=para
rword2=word1[69::-1]
print(rword2)
myspaceremove=rword2.replace(" ", "")
myspaceremove=myspaceremove.replace(" ", "")
myword= special2.join(myspaceremove)
print(myword)
if all(SearchStr in para for SearchStr in list1):
print("Every string in %s were present" %list1)
else:
print("Every string in %s were not present" %list1)
number=word1
splitAll = number.split()
print(splitAll[0:20])
mylist=[]
myDict = dict()
for t in splitAll:
myDict[t]=myDict.get(t,0)+1
for x,y in myDict.items():
if(y<3):
mylist.append(x)
print(mylist[-20:])
print(word1.rfind(strfind))