Write python code to count frequency of each characters in a given file.
Sol:- This program reads a file and counts how many times each character appears.
# Open the file in read mode
file = open("sample.txt", "r")
# Read the file content
text = file.read()
# Create an empty dictionary to store character frequencies
char_freq = {}
# Count frequency of each character
for char in text:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
# Print the result
for char, freq in char_freq.items():
print(f"'{char}': {freq}")
file.close()
Write python program to read contents of abc.txt and write same content to
pqr.txt
Sol:- # Open abc.txt in read mode
with open("abc.txt", "r") as source_file:
content = source_file.read()
# Open pqr.txt in write mode and write the content
with open("pqr.txt", "w") as destination_file:
destination_file.write(content)
print("Content copied successfully.")
Design a class student with data members; Name, roll number address.
Create suitable method for reading and printing students details.
Sol:- class Student:
def __init__(self)
self.name = ""
self.roll_no = 0
self.address = ""
def read_details(self):
self.name = input("Enter Name: ")
self.roll_no = int(input("Enter Roll Number: "))
self.address = input("Enter Address: ")
def print_details(self):
print("\n--- Student Details ---")
print("Name :", self.name)
print("Roll No. :", self.roll_no)
print("Address :", self.address)
# Create object of Student class
s1 = Student()
s1.read_details() # Read data from user
s1.print_details() # Display student data
Create a parent class named Animals and a child class Herbivorous which will
extend the class Animal. In the child class Herbivorous over side the method
feed ( ). Create a object of the class Herbivorous and call the method feed
Sol:- # Parent class
class Animals:
def feed(self):
print("Animals eat food.")
# Child class inheriting from Animals
class Herbivorous(Animals):
# Overriding the feed method
def feed(self):
print("Herbivorous animals eat plants.")
# Creating object of child class
h = Herbivorous()
h.feed() # Calls the overridden method
Write Python code for finding greatest among four numbers.
Sol:- # Input four numbers from user
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
d = int(input("Enter fourth number: "))
# Find the greatest number using if-else
if a >= b and a >= c and a >= d:
greatest = a
elif b >= c and b >= d:
greatest = b
elif c >= d:
greatest = c
else:
greatest = d
# Print the result
print("The greatest number is:", greatest)
Write python program to illustrate if else ladder.
Sol: # Input marks from user
marks = int(input("Enter your marks: "))
# if-elif-else ladder
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
elif marks >= 35:
print("Grade: D")
else:
print("Fail")
Write a program to implement the concept of inheritance in python.
Sol: # Parent class
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f"{self.name} makes a sound.")
# Child class inheriting from Animal
class Dog(Animal):
def __init__(self, name, age, breed):
# Calling the parent class constructor
super().__init__(name, age)
self.breed = breed
# Overriding the speak method
def speak(self):
print(f"{self.name} barks.")
# Creating object of Dog (child class)
dog1 = Dog("Buddy", 3, "Golden Retriever")
# Calling methods
dog1.speak() # Calls the overridden method from Dog class
print(f"{dog1.name} is a {dog1.age}-year-old {dog1.breed}.")
Write a program to open a file in write mode and append some contents at
the end of file.
Sol: # Step 1: Open the file in write mode and write initial content
file = open("example.txt", "w")
file.write("This is the first line.\n")
file.close()
# Step 2: Open the same file in append mode and add more content
file = open("example.txt", "a")
file.write("This is an appended line.\n")
file.close()
# Step 3: Read and display the file contents
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Write a program illustrating use of user defined package in python
Sol: Step 1: Create a Package Directory
Let's assume we want to create a package named my_package with the following structure
my_package/
__init__.py
module1.py
module2.py
Step 2: Write Code in Modules
module1.py:
def greet(name):
return f"Hello, {name}!"
module2.py:
def add(a, b):
return a + b
Step 3: Create a Python Script to Use the Package
Assuming the package my_package is in the same directory as the script:
# Importing functions from the user-defined package
from my_package.module1 import greet
from my_package.module2 import add
# Using functions from the package
name = input("Enter your name: ")
print(greet(name)) # Calling the function from module1
x=5
y = 10
print(f"The sum of {x} and {y} is {add(x, y)}.") # Calling the function from module2
Write a program to create class EMPLOYEE with ID and NAME and display its
contents.
Sol: # Creating the EMPLOYEE class
class EMPLOYEE:
def __init__(self, emp_id, name):
self.emp_id = emp_id # Employee ID
self.name = name # Employee Name
def display(self):
# Displaying employee details
print(f"Employee ID: {self.emp_id}")
print(f"Employee Name: {self.name}")
# Creating an object of EMPLOYEE class
employee1 = EMPLOYEE(101, "John Doe")
# Calling the display method
employee1.display()
Write a program to print following : 1 1 2 1 2 3 1 2 3 4
Sol: # Loop to print the pattern
for i in range(1, 5): # Outer loop for each row
for j in range(1, i + 1): # Inner loop for printing numbers
print(j, end=" ") # Print numbers in the same line
print() # New line after each row
Explain multiple inheritance and write a python program to implement it.
Sol: Multiple inheritance occurs when a class is derived from more than one parent class. This allows
the child class to inherit attributes and methods from multiple parent classes, providing flexibility
and code reuse. In Python, multiple inheritance is possible, and a class can inherit from more than
one parent class.
Program to Implement Multiple Inheritance:
# Parent class 1
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
# Parent class 2
class Mammal:
def __init__(self, habitat):
self.habitat = habitat
def describe_habitat(self):
print(f"{self.habitat} is the natural habitat.")
# Child class inheriting from both Animal and Mammal
class Dog(Animal, Mammal):
def __init__(self, name, habitat, breed):
Animal.__init__(self, name) # Calling constructor of Animal
Mammal.__init__(self, habitat) # Calling constructor of Mammal
self.breed = breed
def display_info(self):
print(f"Name: {self.name}")
print(f"Breed: {self.breed}")
print(f"Habitat: {self.habitat}")
# Creating an object of Dog class
dog1 = Dog("Buddy", "House", "Golden Retriever")
# Calling methods from both parent classes
dog1.speak() # From Animal class
dog1.describe_habitat() # From Mammal class
dog1.display_info() # From Dog class
Write a python program to generate five random integers between 10 and 50
using numpy library
Sol: To generate random integers in Python, you can use the numpy library's random.randint()
function. Here's how to generate five random integers between 10 and 50.
import numpy as np
# Generate five random integers between 10 and 50
random_integers = np.random.randint(10, 51, size=5)
# Print the generated random integers
print("Random integers between 10 and 50:", random_integers)