22.
Perform following operations on a list of numbers:
1) Insert an element 2)
2) delete an element
3) sort the list
4) delete entire list
1) To insert an element
numbers = []
element = int(input("Enter the element to insert:
")) numbers.append(element) print("Updated list:",
numbers)
OUTPUT:-
2) delete an element
numbers = [5, 3, 8, 6, 1]
print("Current list:", numbers)
element = int(input("Enter the element to delete: "))
if element in numbers:
numbers.remove(element)
print(f"Element {element} deleted.") else:
print("Element not found in the list.")
print("Updated list:", numbers)
Page | 22 vikash kumar
OUTPUT:-
3) sort the list numbers
= [5, 3, 8, 6, 1]
print("Original list:",
numbers) numbers.sort()
print("Sorted list:", numbers)
OUTPUT:-
4) delete entire list numbers
= [5, 3, 8, 6, 1]
print("Current list:", numbers)
numbers.clear() print("List after
deletion:", numbers)
OUTPUT:-
Page | 23 Vikash kumar
23 Display word after Sorting in alphabetical order.
words = input("Enter words separated by spaces: ").split()
words.sort() print("Sorted words:", words)
OUTPUT:-
Page | 24 vikash kumar
24 Perform sequential search on a list of given
numbers.
numbers_list = [3, 5, 7, 9, 11]
target_value = 7 found = False
for i in range(len(numbers_list)):
if numbers_list[i] == target_value:
print(f"Target {target_value} found at index {i}.")
found = True
break
if not found: print(f"Target {target_value}
not found.")
OUTPUT:-
Page | 25 Vikash kumar
25 Perform sequential search on ordered list of given
numbers.
ordered_numbers = [1, 3, 5, 7, 9, 11, 13, 15]
target = 7
for i in range(len(ordered_numbers)):
if ordered_numbers[i] == target:
print(f"Target {target} found at index {i}.")
break
elif ordered_numbers[i] > target:
print(f"Target {target} not found (stopped early).")
break
else: print(f"Target {target} not
found.")
OUTPUT:-
Page | 26 vikash kumar
26. Maintain practical note book as per their serial numbers in library
using Python dictionary.
notebooks = {}
notebooks[101] = {"title": "Python Programming", "author": "John Doe"}
notebooks[102] = {"title": "Data Science Handbook", "author": "Jane Smith"}
print("Notebooks in the library:") for serial, details in notebooks.items():
print(f"Serial Number: {serial}, Title: {details['title']}, Author: {details['author']}")
OUTPUT:-
Page | 27 Vikash kumar
27.Perform following operations on dictionary 1) Insert 2) delete 3)
change
1) Insert
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York' print(my_dict)
OUTPUT:-
2) delete
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New
York'} del my_dict['city'] print(my_dict)
OUTPUT:-
3) change
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New
York'} my_dict['age'] = 26 # Update age
print(my_dict)
OUTPUT:-
Page | 28 vikash kumar
28 Check whether a number is in a given range using functions.
def is_number_in_range(number, start, end):
"""Check if the number is within the specified range (inclusive)."""
return start <= number <= end
num = 10
start_range = 5
end_range = 15
if is_number_in_range(num, start_range, end_range):
print(f"{num} is within the range of {start_range} to {end_range}.") else:
print(f"{num} is outside the range of {start_range} to {end_range}.")
OUTPUT:-
Page | 29 Vikash kumar
29. Write a Python function that accepts a string and calculates number
of upper case letters and lower case letters available in that string
def count_case_letters(input_string):
upper_case_count = 0
lower_case_count = 0
for char in input_string:
if char.isupper():
upper_case_count += 1
elif char.islower():
lower_case_count += 1
return upper_case_count, lower_case_count
test_string = "SUMIT Kumar!"
upper_count, lower_count = count_case_letters(test_string)
print(f"Uppercase letters: {upper_count}") print(f"Lowercase
letters: {lower_count}")
OUTPUT:-
Page | 30 vikash kumar
30. To find the Max of three numbers using functions.
def find_max(a, b, c): max_num
=a
if b > max_num:
max_num = b
if c > max_num: max_num
=c
return max_num
num1 = 10 num2 =
25 num3 = 15
max_value = find_max(num1, num2, num3)
print(f"The maximum of {num1}, {num2}, and {num3} is: {max_value}")
OUTPUT:-
Page | 31 Vikash kumar
31 Multiply all the numbers in a list using functions.
def multiply_list(numbers):
product = 1 for num in
numbers:
product *= num
return product
numbers = [2, 3, 4, 5] result =
multiply_list(numbers)
print(f"The product of the numbers in the list {numbers} is: {result}")
OUTPUT:-
Page | 32 vikash kumar
32 Solve the Fibonacci sequence using recursion.
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
result = fibonacci(10) # Get the 10th Fibonacci number
print(result)
OUTPUT:-
Page | 33 Vikash kumar
33 Get the factorial of a non-negative integer using recursion.
def factorial(n): if n
== 0 or n == 1:
return 1
return n * factorial(n - 1)
result = factorial(5) print(result)
OUTPUT:-
Page | 34 vikash kumar
34 Write a program to create a module of factorial in Python.
import math
n = int(input("Enter Any Integer Value: "))
if n < 0: print("Kindly enter a positive
value.")
elif n == 0:
print("Factorial of 0 is: 1") else:
print("Factorial of", n, "is:", math.factorial(n))
OUTPUT:-
Page | 35 Vikash kumar
35 Design a Python class named Rectangle, constructed by a length &
width, also design a method which will compute the area of a
rectangle.
class Rectangle:
def __init__(self, length, width):
"""Initialize the length and width of the
rectangle.""" self.length = length self.width = width
def area(self):
"""Compute the area of the rectangle."""
return self.length * self.width
rect = Rectangle(5, 3)
print(f"The area of the rectangle is: {rect.area()}")
OUTPUT:-
Page | 36 vikash kumar
36 Design a Python class named Circle constructed by a radius and
two methods which will compute the area and the perimeter of a
circle.
import math
class Circle:
def __init__(self, radius):
"""Initialize the radius of the circle."""
self.radius = radius
def area(self):
"""Compute the area of the circle."""
return math.pi * (self.radius ** 2)
def perimeter(self):
"""Compute the perimeter (circumference) of the circle."""
return 2 * math.pi * self.radius
circle = Circle(5)
print(f"The area of the circle is: {circle.area():.2f}") print(f"The
perimeter of the circle is: {circle.perimeter():.2f}")
OUTPUT:-
Page | 37 Vikash kumar
37. Design a Python class to reverse a string ‘word by word’.
class StringReverser: def
__init__(self, text):
"""Initialize the class with the input string.""" self.text
= text
def reverse_words(self):
"""Reverse the string word by word."""
words = self.text.split() reversed_words
= words[::-1]
return ' '.join(reversed_words)
reverser = StringReverser("Hello world this is a test")
result = reverser.reverse_words() print(result)
OUTPUT:-
Page | 38 vikash kumar
38. Write a Python program to read an entire text file.
def read_file(file_path):
try: with open(file_path, 'r') as
file:
content = file.read() return
content
except FileNotFoundError:
return "Error: The file was not found."
except IOError:
return "Error: An I/O error occurred."
file_path = 'example.txt' file_content
= read_file(file_path)
print(file_content)
OUTPUT:-
Page | 39 Vikash kumar
39. Design a Python program to read first n lines of a text file.
file_path = 'example.txt'
n=5
try:
with open(file_path, 'r') as file:
for _ in range(n): line
= file.readline() if
not line:
break
print(line, end='')
except FileNotFoundError:
print("Error: The file was not found.")
OUTPUT:-
Page | 40 vikash kumar