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

Python Func& Oops Handson

The document contains code snippets and definitions for various Python concepts like functions, classes, exceptions, modules and collections. Some key snippets include: 1. Functions for handling exceptions, iterating through lists and generators, prime number generation. 2. Classes for movies, complex numbers, inheritance for assets distribution. 3. Modules for date/time, itertools, cryptography, calendar. 4. Collections examples using Counter, dictionaries, splitting text. The document covers a wide range of Python topics through examples to demonstrate concepts like functions, classes, exceptions, modules and collections.

Uploaded by

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

Python Func& Oops Handson

The document contains code snippets and definitions for various Python concepts like functions, classes, exceptions, modules and collections. Some key snippets include: 1. Functions for handling exceptions, iterating through lists and generators, prime number generation. 2. Classes for movies, complex numbers, inheritance for assets distribution. 3. Modules for date/time, itertools, cryptography, calendar. 4. Collections examples using Counter, dictionaries, splitting text. The document covers a wide range of Python topics through examples to demonstrate concepts like functions, classes, exceptions, modules and collections.

Uploaded by

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

Handling 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 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")  

1. Hands on python string methods


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))

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

CLASSES AND OBJECTS 1 TASK


1
class Movie:
    def __init__(self, val1, val2, val3):
      self.movieName= val1
      self.numberTickets = val2
      self.totalCost = val3
    def __str__(self):
    #return self.movieName
    #return self.numberTickets
    #return self.totalCost
     return "Movie : {}\nNumber of Tickets : {}\nTotal Cost : {}
".format(self.   movieName,self.numberTickets,self.totalCost)

CLASSES AND OBJECTS 1 TASK


2
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". format
   (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". form
at(self.a - other.a, self.b - other.b))

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]
, tup [4], tup[5])
   l.append(c1)
 return l

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 and Objects 2:


Task1:
class parent:
    def __init__(self, t):
     self.t = t
    def display (self):
     print("Share of Parents is {} Million.".format(round((
   self. 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(Percentage_fo
r_son, 2)))
     print("Total Asset Worth is {} Million.". format(round
   (self.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(Percen
tage_for_daughter, 2)))
     print("Total Asset Worth is {} Million.".format(round(self.t, 
2)))

Class and Objects 2:


Task 2:

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))

You might also like