Sunday, 29 November 2020

User defined Exceptions in Python

#USER DEFINED EXCEPTION

Here MyException is an userdefined class and it must be inherited from the base class Exception.

Create a constructor and send the error message to it.

class MyException(Exception):
    def __init__(self,value):
        self.value=value
    def __str__(self):
        return(repr(self.value))
try:
    raise(MyException("This is my user defined Exception"))
except MyException as e:
    print("Printable Message:",e.value)

#USER DEFINED EXCEPTION WITH INHERITANCE 

class MyException(Exception):
     pass
class Dividebyzero(MyException):
      pass
try:
    a = int(input("Enter a value: "))
    b=int(input("Enter b value: "))
    if b==0:
        raise Dividebyzero
    else:
        print("result=",(a/b))
except Dividebyzero:
    print("Dont enter Input value for b as zero, try again!")
#FINALLY KEYWORD

try:
    a=int(input("enter value for a"))
    b=int(input("enter value for b"))
    c=a/b
    print(c)
except ZeroDivisionError:    
    print("Dont enter b value as zero")    
finally:    
    print('This is always executed')  

Tuesday, 24 November 2020

Inheritance in Python

 

 

 #Multiple Inheritance

class Father:
    def reading1():
        Father.height1=int(input("Enter Fathers Height"))
    def printing1():
        print("Fathers height: ",Father.height1)
class Mother:
    def reading2():
        Mother.height2=int(input("Enter mothers Height"))
    def printing2():
        print("Mothers height: ",Mother.height2)
class child(Father,Mother):
    def calculate():
        child.height3=(Father.height1+Mother.height2)/2
    def printing():
        print(child.height3)
Father.reading1()
Father.printing1()
Mother.reading2()
Mother.printing2()
child.calculate()
child.printing()       

OUTPUT: