Practical 20
Q.1 Write a Python class to implement pow (x, n).
class Power:
def compute(self, x, n):
return x ** n
p = Power()
print(p.compute(2, 3))
Q.2 Write a Python class to reverse a string word by word.
class ReverseString:
def reverse(self, text):
return ' '.join(text.split()[::-1])
r = ReverseString()
print(r.reverse("Hello World"))
Q.3 Write a Python class to convert an integer to a roman numeral.
class IntegerToRoman:
def convert(self, num):
roman_map = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X',
9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
roman = ''
for value in roman_map:
while num >= value:
roman += roman_map[value]
num -= value
return roman
r = IntegerToRoman()
print(r.convert(960))
Q.4 Write a Python class that has two methods: get_String and print_String, get_String accept a
string from the user and print_String prints the string in upper case.
class StringOperations:
def get_and_print(self):
text = input("Enter a string: ")
print(text.upper())
s = StringOperations()
s.get_and_print()
Q.5 Write a Python class named Rectangle constructed from length and width and a method that
will compute the area of a rectangle.
class Rectangle:
def area(self, length, width):
return length * width
r = Rectangle()
print(r.area(5, 3))