Programming With Python Practical 14

Question 1
Write a Python program to create a class to print an integer and a character with two methods having the same name but different sequence of the integer and the character parameters. For example, if the parameters of the first method are of the form (int n, char c), then that of the second method will be of the form (char c, int n)
numchar.py
class data:
    def getdata(self,x,cha):
        if(str(x).isnumeric() and cha.isalpha()):
            print(f"Number is {x} and character is '{cha}'")
        elif(x.isalpha() and str(cha).isdigit()):
            print(f"Character is '{x}' and number is {cha}")

d=data()
num=int(input("Enter a number: "))
ch=input("Enter a character: ")[0]
d.getdata(num,ch)
d.getdata(ch,num)
Output
Question 2
Write a Python program to create a class to print the area of a square and a rectangle. The class has two methods with the same name but different number of parameters. The method for printing area of rectangle has two parameters which are length and breadth respectively while the other method for printing area of square has one parameter which is side of square.
shapes.py
class shape:
    def area(self,x,y=None):
        if(y==None):
            a=x*x
            print("Area of square is: ",a)
        else:
            a=x*y
            print("Area of rectangle is: ",a)

sh=shape()
l=int(input("Enter length of rectangle: "))
w=int(input("Enter width of rectangle: "))
sh.area(l,w)
s=int(input("Enter side of a aquare: "))
sh.area(s)
Output
Question 3
Write a Python program to create a class 'Degree' having a method 'getDegree' that prints "I got a degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate' each having a method with the same name that prints "I am an Undergraduate" and "I am a Postgraduate" respectively. Call the method by creating an object of each of the three classes.
degrees.py
class Degree:
    def getDegree(self):
        print("I got a degree")

class Undergraduate(Degree):
    def getDegree(self):
        print("I am undergraduate")

class Postgraduate(Degree):
    def getDegree(self):
        print("I am postgraduate")

d=Degree()
d.getDegree()

ug=Undergraduate()
ug.getDegree()

pg=Postgraduate()
pg.getDegree()
Output

Leave a Comment

Your email address will not be published. Required fields are marked *