Python Mannual
Python Mannual
Program:
def capitalize_first_and_last(string):
if len(string) < 2:
return string
first_letter = string[0].upper()
last_letter = string[-1].upper()
middle_letters = string[1:-1]
return first_letter + middle_letters + last_letter
# Example usage
input_string = input("Enter a string: ")
result = capitalize_first_and_last(input_string)
print("Result:", result)
Output:
2. Write a python program for the following.
i) Create list of fruits
ii) Add new fruit in list.
iii) Sort the list.
iv) Delete last fruit name from list
Program:
Fruits=['Apple','Banana','Orange']
print(Fruits)
Fruits.append('Mango')
Fruits.sort()
Fruits.pop()
Output:
3. Write a program for tuple &set operations?
Program:
Tuple:
tuple1=(1,2,3,4,5)
tuple2=(6,7,8)
tuple3=(9,0)
# Concatenating tuples
tuple_concat=tuple1+tuple2
print('concated tuple:',tuple_concat)
# Length of a tuple
set_from_tuple=set(tuple1)
Output:
Sets:
# Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
set3 = {5, 6, 7, 8, 9}
# Set union
set_union = set1.union(set2)
# Set intersection
set_intersection = set1.intersection(set2)
# Set difference
set_difference = set1.difference(set2)
set_sym_difference = set1.symmetric_difference(set2)
Program:
# Dictionary operations
student = {
'grade': 'A'}
student['age'] = 21
student['grade'] = 'B'
del student['grade']
number = 16
square_root = sqrt(number)
Program:
import os
main_dir = "C:/mypack"
os.mkdir(main_dir)
import os
main_dir = "C:/Practice/subpackage"
os.mkdir(main_dir)
Output:
6. Write a program Reading and Writing file?
Program:
# File path
file_path = "example.txt"
file.write("Hello, World!\n")
content = file.read()
print("File Contents:")
print(content)
Output:
7. Write a program Reading and Writing into Binary file?
Program:
# File path
file_path = "example.bin"
file.write(data_to_write)
content = file.read()
print("File Contents:")
print(content)
Output:
8. Write a program to create text file?
Program:
# File path
file_path = "filecreate.txt"
file.write(content)
Output:
9. Write a python code to diplay first m and last n lines from text file?
Program:
lines = file.readlines()
print(line.strip())
print(line.strip())
# File path
display_first_and_last_lines(file_path, m, n)
Output:
10. Write a program to create user defined exception not prime if given number is not prime else
print the prime number?
Program:
class NotPrimeError(Exception):
pass
def is_prime(number):
if number < 2:
return False
if number % i == 0:
return False
return True
try:
if is_prime(number):
else:
except ValueError:
except NotPrimeError as e:
print(e)
Output:
11. Write a program to replace the last three characters of string with ‘ing’,if having’ing’ inthe string
then replace by ‘ly’?
Program:
def replace_last_three_chars(string):
if string.endswith("ing"):
else:
result = replace_last_three_chars(string)
Output:
12. Write a program that accept the string from user and display the same string after removing
vowels from it?
Program:
def remove_vowels(string):
result = ""
result += char
return result
result = remove_vowels(string)
Output:
13. Create class called, library with data attributes like Acc-number publisher, title and author,
the methods of the class should include- i) Read ( ) - Acc- number, title, author,publisher. ii)
Compute ( ) - to accept the number of day late, calculate and display the fine charged at the
rate of Rupees 5/- per day. iii) Display the data?
Program:
class Library:
self.acc_number = acc_number
self.publisher = publisher
self.title = title
self.author = author
def read(self):
print("Title:", self.title)
print("Author:", self.author)
print("Publisher:", self.publisher)
fine = days_late * 5
def display(self):
print("Title:", self.title)
print("Author:", self.author)
print("Publisher:", self.publisher)
# Example usage:
book1.read()
book1.compute(10)
book1.display()
Output:
14. Develop a program to print the number of lines, words and characters present in the given file?
Accept the file name from user. Handle necessary exceptions?
Program:
def count_lines_words_chars(file_name):
try:
lines = 0
words = 0
characters = 0
lines += 1
words += len(line.split())
characters += len(line)
except FileNotFoundError:
except PermissionError:
count_lines_words_chars(file_name)
Output:
15. Write a program to guess correct no that is 10 and throw user defined exceptionToosmallnumber if number is
small and throw exception Toolargenumber if enterednumber is large?
Program:
class TooSmallNumber(Exception):
pass
class TooLargeNumber(Exception):
pass
def guess_number(guess):
target_number = 10
else:
try:
guess_number(user_guess)
except TooSmallNumber as e:
print(e)
except TooLargeNumber as e:
print(e)
Output:
16. Write a program to demonstrate class and object to create employee class?
Program:
class Employee:
self.emp_id = emp_id
self.name = name
self.salary = salary
def display(self):
print("Name:", self.name)
print("Salary:", self.salary)
print("Employee 1 Information:")
emp1.display()
print("\nEmployee 2 Information:")
emp2.display()
Output:
17. Write a python program to implement student class which has method to calculate percentage.
Assume suitable class variable?
Program:
class Student:
self.name = name
self.roll_number = roll_number
self.marks = marks
Student.total_students += 1
def calculate_percentage(self):
total_marks = sum(self.marks)
return percentage
@classmethod
def display_total_students(cls):
# Example usage:
Student.display_total_students()
Output:
18. Write a program for python constructor and destructor?
Program:
class MyClass:
self.name = name
def __del__(self):
# Deleting objects
del obj1
del obj2
Output:
19. Write a python code to demonstrate multiple and multilevel inheritance?
Program:
class Animal:
self.name = name
def speak(self):
pass
class Mammal(Animal):
super().__init__(name)
def give_birth(self):
class Dog(Mammal):
super().__init__(name)
def speak(self):
return "Woof!"
class Cat(Mammal):
super().__init__(name)
def speak(self):
return "Meow!"
class Bird(Animal):
super().__init__(name)
def fly(self):
print(f"{self.name} is flying...")
class Parrot(Bird):
super().__init__(name)
def speak(self):
return "Squawk!"
if __name__ == "__main__":
dog = Dog("Buddy")
if __name__ == "__main__":
dog = Dog("Buddy")
print(dog.speak())
dog.give_birth()
cat = Cat("Whiskers")
print(cat.speak())
cat.give_birth()
parrot = Parrot("Polly")
print(parrot.speak())
parrot.fly()
Output:
20. Write a program to demonstrate class variable, data hiding, method overriding andoperator overloading?
def __init__(self):
def get_count(self):
return Counter.__count
def __str__(self):
class SpecialCounter(Counter):
return SpecialCounter.__count
def __str__(self):
# Demo
print("Creating Counters:")
c1 = Counter()
c2 = Counter()
sc1 = SpecialCounter()
sc2 = SpecialCounter()
total_count = c1 + sc1
Program:
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if re.match(pattern, email):
return True
else:
return False
def validate_mobile_number(number):
pattern = r'^\d{10}$'
if re.match(pattern, number):
return True
else:
return False
email = "example@example.com"
mobile_number = "1234567890"
if validate_email(email):
print("Email is valid")
else:
print("Email is invalid")
if validate_mobile_number(mobile_number):
else:
Program:
import re
regex = re.compile(pattern)
return result
# Example usage
Output:
23. Write a program to search name and age from given data?
Program:
class Data:
def __init__(self):
self.data = {
"John": 25,
"Jane": 30,
"Alice": 22,
"Bob": 28,
"Emma": 35
if name in self.data:
else:
# Example usage:
Output:
data_obj = Data()
search_name = "Alice"
else:
Program:
import re
"""
Args:
Returns:
"""
# Example usage:
Output:
25. Write a program for addition of matrix and transpose of matrix using list
comprehension?
Program:
def transpose(matrix):
Args:
Returns:
Args:
Returns:
# Example matrices
[4, 5, 6],
[7, 8, 9]]
[6, 5, 4],
[3, 2, 1]]
# Add matrices
# Transpose matrices
transposed_matrix1 = transpose(matrix1)
transposed_matrix2 = transpose(matrix2)
# Transpose matrices
transposed_matrix1 = transpose(matrix1)
transposed_matrix2 = transpose(matrix2)
# Output results
print("Matrix 1:")
print(row)
print("\nMatrix 2:")
print(row)
print(row)
print(row)
print(row)
Output:
26. Write a program to plot a line chart?
Program:
# Displaying
the chart
plt.show()
Output:
27. Write a program to check whether entered string & number is palindrome or not?
Program:
def is_palindrome(input_str):
Args:
Returns:
input_str = str(input_str)
def main():
if is_palindrome(user_input):
else:
if __name__ == "__main__":
main()
Output:
28. Illustrate CRUD operations in MongoDB with example?
Program:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
mycol = mydb["customers"]
inserted_doc = mycol.insert_one(customer_data)
inserted_docs = mycol.insert_many(customer_data_list)
print("One document:")
print(mycol.find_one())
print("\nAll documents:")
print(document)
print(document)
mycol.update_one(query, new_values)
mycol.delete_one(query)
deleted_docs = mycol.delete_many(query)
deleted_all_docs = mycol.delete_many({})
Output:
29. Write a pythan program to perform following operations. on MongoDB Database-
a. Create collection “EMP” with fields: Emp-name, Emp- mobile, Emp, sal, Age
b. Insert 5 documents.
c. Find the employees getting salary between 5000 to 10000.
d. Update mobile number for the employee named as “Riddhi”
e. Display all empolyees in the order of ”Age”
Program: import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
emp_collection = mydb["EMP"]
employees = [
emp_collection.insert_many(employees)
print(employee)
emp_collection.update_one(query, new_values)
# v) Display all employees in the order of "Age"
print(employee)
Output:
30. Write a pythan program to find the factorial of a given number using recursion?
Program:
def factorial(n):
Args:
Returns:
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Output:
31. Write a Python program to check the validity of a password given by user?
Program:
def is_valid_password(password):
# Check length
return False
if is_valid_password(password):
print("Password is valid.")
else:
Output:
32. The password should satisfied
following criteria:
a. Contain at least 1 number between 0 and 9
b. Contain at least 1 letter between A and Z
c. Contain at least 1 character from $, #, @,*
d. Minimum length of password : 8
e. Maximum length of password : 20
Program:
import re
def is_valid_password(password):
Criteria:
Args:
Returns:
# Check length
return False
# Check if password contains at least 1 lowercase letter, 1 uppercase letter, 1 digit, and 1 special character
return False
return False
return False
return False
return True
if is_valid_password(password):
print("Password is valid.")
else:
Output:
33. Draw bar graph using matplotlib and decorate it by adding various elements?
Program:
# Add gridlines
plt.grid(True, linestyle='--', alpha=0.5)
Output:
34. Prepare the pandas dataframe from csv file?
Program:
import pandas as pd
def main():
data = pd.read_csv(r'C:\Users\anike\OneDrive\Desktop\csvexample1.csv')
#df = pd.read_csv(data)
print(data)
if __name__ == "__main__":
main()
Output:
35. perform following operations. i) Fill all ‘NaN’ values with the mean of respective
column. ii) Display last 5 rows. d) Explain constructors in pythan with example.
Program:
36. Write a program to illustrate numpy array attributes/functions.
a. ndarray. Shape
b. np. zeros ( )
c. np. eye ( )
d. np. random. random ( )
Program:
import numpy as np
def main():
# Creating a 2D array
[4, 5, 6]])
print(zeros_arr)
# iii) np.eye() - creates a 2-D array with ones on the diagonal and zeros elsewhere
eye_arr = np.eye(3)
print(eye_arr)
# iv) np.random.random() - returns random floats in the half-open interval [0.0, 1.0)
print("Random array:")
print(random_arr)
if __name__ == "__main__":
main()
Output:
37. Read data from csv five and create dataframe. Perform following operations. i)
Display list of all columns. ii) Display data with last three rows and first three
columns
Program:
import pandas as pd
data = pd.read_csv(r'C:\Users\anike\OneDrive\Desktop\csvexample1.csv')
#df = pd.read_csv('C:\Users\anike\OneDrive\Desktop\csvexample1.csv')
print(data.columns.tolist())
# ii) Display data with last three rows and first three columns
print(data.iloc[-3:, :3])
Output:
38 Draw line graph using matplot lib and decorate it by adding
various elements. Usesuitable data?
Program:
# Add gridlines
plt.grid(True, linestyle='--', alpha=0.5)