MSBTE Python 22616 - Frequently Asked Programs
1. Create a class Student and display contents
class Student:
def __init__(self, roll_no, name):
self.roll_no = roll_no
self.name = name
def display(self):
print("Roll No:", self.roll_no)
print("Name:", self.name)
s1 = Student(101, "Tanmay")
s1.display()
2. Program to implement inheritance
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
d = Dog()
d.sound()
3. Multiple Inheritance
class Father:
def skills(self):
print("Gardening, Programming")
class Mother:
def skills(self):
print("Cooking, Art")
class Child(Father, Mother):
def skills(self):
Father.skills(self)
Mother.skills(self)
print("Dancing")
c = Child()
c.skills()
4. Read contents of first.txt and write to second.txt
with open('first.txt', 'r') as f1:
content = f1.read()
with open('second.txt', 'w') as f2:
f2.write(content)
5. User-defined module example
# module_file.py
def show_name(name):
print("Program name is:", name)
# main_program.py
import module_file
module_file.show_name("PythonBasics")
6. Program to check palindrome number
num = int(input("Enter a number: "))
if str(num) == str(num)[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
7. Sum of digits in a number
num = int(input("Enter number: "))
total = 0
while num > 0:
digit = num % 10
total += digit
num = num // 10
print("Sum of digits:", total)
8. Count uppercase and lowercase letters in a string
s = input("Enter string: ")
upper = lower = 0
for char in s:
if char.isupper():
upper += 1
elif char.islower():
lower += 1
print("Uppercase letters:", upper)
print("Lowercase letters:", lower)
9. Generate 5 random numbers using NumPy
import numpy as np
rand_nums = np.random.randint(10, 51, size=5)
print("Random numbers:", rand_nums)
10. String slicing operations
fruit = 'banana'
print(fruit[:3]) # ban
print(fruit[3:]) # ana
print(fruit[3:3]) # (empty)
print(fruit[:]) # banana
print(fruit[-1]) # a
print(fruit[1]) # a
11. Use of user-defined exception
class PasswordError(Exception):
pass
password = input("Enter password: ")
try:
if password != "admin123":
raise PasswordError
else:
print("Password is correct")
except PasswordError:
print("Incorrect password")