0% found this document useful (0 votes)
3 views32 pages

Programming in Python Practical

Uploaded by

lzhqwbsjn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

Programming in Python Practical

Uploaded by

lzhqwbsjn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Assignment : 1

Develop a Python program that reads marks from three different subjects and
calculates their average.

Source Code :-
Mark1 = float(input(“Enter marks of Subject 1: “))
Mark2 = float(input(“Enter marks of Subject 2: “))
Mark3 = float(input(“Enter marks of Subject 3: “))
Average = (mark1 + mark2 + mark3) / 3
Print(“Average Marks =”, average)

Output :-
Enter marks of Subject 1: 85
Enter marks of Subject 2: 78
Enter marks of Subject 3: 92
Average Marks = 85.0

Conclusion :-
The program successfully reads the marks of three subjects, calculates their average using the
average formula, and displays the result correctly. It demonstrates the use of user input, arithmetic
operations, variables, and output statements in Python.

Assignment : 2
Write a program to display Pascal’s Triangle.
Source Code :-
N = int(input(“Enter the number of rows: “))
For I in range(n):
Num = 1
For j in range(n – i):
Print(“ “, end=””)
For j in range(I + 1):
Print(num, end=” “)
Num = num * (I – j) // (j + 1)
Print()

Output :-
Enter the number of rows: 5
1
11
121
1331
14641

Conclusion :-
The program successfully displays Pascal’s Triangle for the given number of rows. It demonstrates
the use of nested loops, arithmetic operations, and pattern generation in Python while calculating
each element of Pascal’s Triangle efficiently without using factorials.

Assignment : 3
Write
Write a program
a program to display
to display the following
the following pattern
pattern using nestedusing
loops. nested loops.
11 11
22 21
333 321 1
4444 4321
55555 54321
22 21
333 321
4444 4321
55555 54321

Source Code :-
for i in range(1, 6):
for j in range(i):
print(i, end="")
print(" ", end="")
for j in range(i, 0, -1):
print(j, end="")
print()

Output :-

1 1
22 21
333 321
4444 4321
55555 54321

Conclusion :-

The program successfully prints the required pattern using nested loops. It demonstrates the use of for loops,
loop nesting, and pattern generation techniques in Python by printing repeated and descending numbers in
each row.

Assignment : 4 & 5
Write a program to print the sum of the following series:
Write a program to print the sum of the following series
1a.
+ 1 + ½ + 1/3
\frac{1}{2} +. …. + 1/n
+ \frac{1}{3} + \cdots + \frac{1}{n}
b. 1/1 + 2²/2 + 3³/3 + ……. + n^n/n

Source Code :-
n = int(input("Enter the value of n: "))
sum = 0
for i in range(1, n + 1):
sum = sum + (1 / i)
print("Sum of the series =", sum)

m = int(input("Enter the value of m: "))


sum2 = 0
for j in range(1, m + 1):
sum2 = sum2 + (j ** j) / j
print("Sum of the series =", sum2)

Output :-

Enter the value of n: 5


Sum of the series = 2.283333333333333

Enter the value of n: 4


Sum of the series = 76.0

Conclusion :-
The program successfully calculates the sum of the series using a for loop. It demonstrates the
use of loops, arithmetic operations, and user input in Python. The program successfully computes
the sum of the given mathematical series using a for loop and exponentiation. It demonstrates the
use of loops, arithmetic expressions, and user input to solve series-based problems in Python.

Assignment : 6
Write a program to sort a string lexicographically.
Write a program to replace a string with another string without using built-in methods.
Write a program to concatenate two strings into another string without using the + operator.
Write a program to strip a set of characters from a string.
Write a program to extract the first n characters of a string.

2
Source Code :-
string = input("Enter a string: ")
sorted_string = ''.join(sorted(string))
print("Sorted String =", sorted_string)

string = input("Enter original string: ")


old = input("Enter string to replace: ")
new = input("Enter new string: ")
result = ""
i = 0
while i < len(string):
if string[i:i+len(old)] == old:
result += new
i += len(old)
else:
result += string[i]
i += 1
print("Modified String =", result)

str1 = input("Enter first string: ")


str2 = input("Enter second string: ")
result = "".join([str1, str2])
print("Concatenated String =", result)

string = input("Enter a string: ")


chars = input("Enter characters to remove: ")
result = ""
for ch in string:
if ch not in chars:
result += ch
print("Result =", result)

string = input("Enter a string: ")


n = int(input("Enter value of n: "))
print("First", n, "characters =", string[:n])

Output :-
Enter a string: python
Sorted String = hnopty

Enter original string: I like apples


Enter string to replace: apples
Enter new string: mangoes
Modified String = I like mangoes

Enter first string: Hello


Enter second string: World
Concatenated String = HelloWorld

Enter a string: programming


Enter characters to remove: gm
Result = prorain

Enter a string: PythonProgramming


Enter value of n: 6
First 6 characters = Python

Conclusion :-
The programs successfully perform different string manipulation operations such as sorting, replacing,
concatenating, removing specific characters, and extracting a substring. They demonstrate the use of string
handling techniques, loops, indexing, slicing, and user input in Python.

Assignment : 7
Write a program that creates a list of 10 random integers. Then create two lists by name odd_list
and even_list that have all odd and even values of the list respectively.
Source Code :-

import random
numbers = []

3
for i in range(10):
[Link]([Link](1, 100))
odd_list = []
even_list = []
for num in numbers:
if num % 2 == 0:
even_list.append(num)
else:
odd_list.append(num)
print("Original List :", numbers)
print("Odd List :", odd_list)
print("Even List :", even_list)

Output :-

Original List : [12, 45, 67, 88, 23, 10, 55, 76, 91, 34]
Odd List : [45, 67, 23, 55, 91]
Even List : [12, 88, 10, 76, 34]

Conclusion :-

The program successfully generates a list of 10 random integers and separates them into two different lists
containing odd and even numbers. It demonstrates the use of lists, loops, conditional statements, and the
random module in Python.

Assignment : 8
Make a list of the first eight letters of the alphabet. Then, using the slice operation, perform the
following operations:
Print the first three letters of the alphabet.
Print any three letters from the middle.
Print the letters from any particular index to the end of the list.
Source Code :-
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print("First three letters:", alphabet[:3])
print("Middle three letters:", alphabet[2:5])
print("Letters from index 4 to end:", alphabet[4:])

Output :-
First three letters: ['a', 'b', 'c']
Middle three letters: ['c', 'd', 'e']
Letters from index 4 to end: ['e', 'f', 'g', 'h']

Conclusion :-

The program successfully demonstrates list slicing in Python. It shows how to extract elements from the
beginning, middle, and end of a list using slice notation. This practical helps in understanding indexing and
slicing operations on lists.

Assignment : 9
Write a function that prompts the user to enter five numbers. Then invoke the function to find the
GCD (Greatest Common Divisor) of these numbers.

Source Code :-
from math import gcd
def find_gcd(numbers):

4
result = numbers[0]
for num in numbers[1:]:
result = gcd(result, num)
return result
numbers = []
for i in range(5):
num = int(input("Enter number {}: ".format(i + 1)))
[Link](num)
print("GCD =", find_gcd(numbers))

Output :-

Enter number 1: 24
Enter number 2: 36
Enter number 3: 48
Enter number 4: 60
Enter number 5: 72
GCD = 12

Conclusion :-

The program successfully accepts five numbers from the user and determines their Greatest Common Divisor
(GCD) using a user-defined function. It demonstrates the use of functions, loops, lists, and the gcd() function
from Python's math module to solve the problem efficiently.

Assignment : 10
Write a function named addfruit, which is passed a set of fruit names and their prices and returns
a dictionary containing the entered information. The function should raise a ValueError exception if
the fruit is already present in the dictionary.
Source Code :-
def addfruit(fruit_dict, fruit_name, price):
if fruit_name in fruit_dict:
raise ValueError("Fruit already exists!")
fruit_dict[fruit_name] = price
return fruit_dict
fruits = {}
try:
addfruit(fruits, "Apple", 120)
addfruit(fruits, "Banana", 40)
addfruit(fruits, "Mango", 80)
addfruit(fruits, "Apple", 150)
except ValueError as e:
print(e)
print("Fruit Dictionary:")
print(fruits)

Output :-

Fruit already exists!


Fruit Dictionary:
{'Apple': 120, 'Banana': 40, 'Mango': 80}

Conclusion :-

The program successfully stores fruit names and their prices in a dictionary using a user-defined function. It
also demonstrates exception handling by raising a ValueError when a duplicate fruit name is entered, ensuring
that duplicate entries are not added to the dictionary.

Assignment : 11
Create a dictionary that contains usernames as the keys and passwords as the associated values.
Make up the data for five dictionary entries and demonstrate the use of clear() and fromkeys()
methods.
Source Code :-

users = {
"Rahul": "rahul123",
"Amit": "amit456",
"Riya": "riya789",

5
"Sneha": "sneha321",
"Ankit": "ankit654"
}
print("Original Dictionary:")
print(users)
keys = ["User1", "User2", "User3"]
new_users = [Link](keys, "password")
print("\nDictionary created using fromkeys():")
print(new_users)
[Link]()
print("\nDictionary after clear():")
print(users)

Output :-

Original Dictionary:
{'Rahul': 'rahul123', 'Amit': 'amit456', 'Riya': 'riya789',
'Sneha': 'sneha321', 'Ankit': 'ankit654'}
Dictionary created using fromkeys():
{'User1': 'password', 'User2': 'password', 'User3': 'password'}
Dictionary after clear():
{}

Conclusion :-

The program successfully creates a dictionary containing usernames and passwords. It demonstrates the use of
the fromkeys() method to create a new dictionary with common default values and the clear() method to
remove all items from a dictionary. This practical helps in understanding basic dictionary operations in Python.

Assignment : 12
Write a program that has a dictionary of your friends' names as keys and phone numbers as values.
Print the dictionary in sorted order. Prompt the user to enter a name and check whether it is
present in the dictionary. If the name is not present, then enter the details into the dictionary.

Source Code :-
friends = {
"Rahul": "9876543210",
"Amit": "8765432109",
"Riya": "7654321098"
}
print("Friends Dictionary (Sorted Order):")
for name in sorted(friends):
print(name, ":", friends[name])
search = input("\nEnter friend's name to search: ")
if search in friends:
print("Phone Number:", friends[search])
else:
phone = input("Name not found.\nEnter phone number: ")
friends[search] = phone
print("\nUpdated Dictionary:")
for name in sorted(friends):
print(name, ":", friends[name])

Output :-

Friends Dictionary (Sorted Order):


Amit : 8765432109
Rahul : 9876543210
Riya : 7654321098
Enter friend's name to search: Sneha
Name not found.
Enter phone number: 9123456789
Updated Dictionary:
Amit : 8765432109
Rahul : 9876543210
Riya : 7654321098
Sneha : 9123456789

Conclusion :-

6
The program successfully stores friends' names and phone numbers in a dictionary, displays the entries in
sorted order, searches for a given name, and adds a new entry if the name is not found. It demonstrates the
use of dictionaries, sorting, conditional statements, and user input in Python.

Assignment : 13
Write a program to create a dictionary containing the author names as the keys and ISBN numbers
as the values. Make up the data for five dictionary entries and demonstrate the use of clear() and
fromkeys() methods.
Source Code :-
authors = {
"R.K. Narayan": "9788172234980",
"Chetan Bhagat": "9788129135728",
"Ruskin Bond": "9780143333388",
"Rabindranath Tagore": "9788171678938",
"Arundhati Roy": "9780679457312"
}
print("Original Dictionary:")
print(authors)

7
keys = ["Book1", "Book2", "Book3"]
books = [Link](keys, "ISBN Not Assigned")
print("\nDictionary created using fromkeys():")
print(books)
[Link]()
print("\nDictionary after clear():")
print(authors)

Output :-
Original Dictionary:
{
'R.K. Narayan': '9788172234980',
'Chetan Bhagat': '9788129135728',
'Ruskin Bond': '9780143333388',
'Rabindranath Tagore': '9788171678938',
'Arundhati Roy': '9780679457312'
}
Dictionary created using fromkeys():
{
'Book1': 'ISBN Not Assigned',
'Book2': 'ISBN Not Assigned',
'Book3': 'ISBN Not Assigned'
}
Dictionary after clear():
{}
Conclusion :-
The program successfully creates a dictionary with author names as keys and ISBN numbers as values. It
demonstrates the use of the fromkeys() method to create a new dictionary with default values and the
clear() method to remove all elements from a dictionary. This practical helps in understanding dictionary
creation and built-in dictionary methods in Python.

Assignment : 14
Write a program to create the intersection, union, set difference, and symmetric difference of two
sets.

Source Code :-
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("Set 1 =", set1)
print("Set 2 =", set2)
print("Union =", [Link](set2))
print("Intersection =", [Link](set2))
print("Difference (Set1 - Set2) =", [Link](set2))
print("Symmetric Difference =", set1.symmetric_difference(set2))

Output :-
Set 1 = {1, 2, 3, 4, 5}
Set 2 = {4, 5, 6, 7, 8}
Union = {1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {4, 5}
Difference (Set1 - Set2) = {1, 2, 3}
Symmetric Difference = {1, 2, 3, 6, 7, 8}

Conclusion :-
The program successfully performs the basic set operations in Python: union, intersection, difference, and
symmetric difference. It demonstrates how Python's built-in set methods can be used to compare and
manipulate sets efficiently.

Assignment : 15
Write a program to demonstrate the use of issubset() and issuperset()
Source Code :-
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print("Set 1 =", set1)
print("Set 2 =", set2)
print("Is Set 1 a subset of Set 2?", [Link](set2))
print("Is Set 2 a superset of Set 1?", [Link](set1))

Output :-

8
Set 1 = {1, 2, 3}
Set 2 = {1, 2, 3, 4, 5}
Is Set 1 a subset of Set 2? True
Is Set 2 a superset of Set 1? True

Conclusion :-

The program successfully demonstrates the use of the issubset() and issuperset() methods in Python. It
verifies whether one set is a subset of another and whether the other set is its superset, helping to understand
the relationship between two sets.

Assignment : 16
Here is an example dictionary. You may insert more data of your choice. Write a program in Python
that reads the dictionary and prints the following:
(a) All the users whose phone number ends in 5.
(b) All the users that don't have an email address listed.
(c) All the users whose phone number starts with 9.
Source Code :-
users = [
{"name": "Ram", "phone": "9434141414", "email": "ram@[Link]"},
{"name": "Laksman", "phone": "8434151515"},
{"name": "Bharat", "phone": "7474161616", "email": "bharat@[Link]"},
{"name": "Satrughna", "phone": "9478171717", "email": "satrughna@[Link]"}
]
print("Users whose phone number ends with 5:")
for user in users:
if user["phone"].endswith("5"):
print(user["name"])
print("\nUsers without an email address:")
for user in users:
if "email" not in user:
print(user["name"])
print("\nUsers whose phone number starts with 9:")
for user in users:
if user["phone"].startswith("9"):
print(user["name"])

Output :-

Users whose phone number ends with 5:


Laksman
Users without an email address:
Laksman
Users whose phone number starts with 9:
Ram
Satrughna

Conclusion :-

The program successfully processes a list of dictionaries containing user information. It identifies users whose
phone numbers end with 5, users who do not have an email address, and users whose phone numbers start
with 9. This practical demonstrates the use of lists, dictionaries, loops, conditional statements, and
string methods in Python.

Assignment : 17
Write a program in Python that populates an empty list with integers, each of which are either 0 or
Example: If the list is [1,0,1,0,0,0,1,0,0,0,0,0,0,1], then the longest run of zeros is 6, and the span of
1. Then find the size of the longest chain of zeros. Also give the span of indices containing the
indices is 7 to 12.
longest chain.
Source Code :-
import random
num=[]
for i in range(15):
[Link]([Link](0,1))
print(num)
i=0
max = 0
start=end=-1

9
while i < len(num):
if num[i]==0:
s=i
count=0
while i < len(num) and num[i] == 0:
count = count +1
i=i+1
if count > max:
max = count
start = s
end = i-1
else:
i=i+1
print(max)
print("span",start,"to",end)

Output :-

[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1]
5
span 2 to 6

Conclusion :-

The program successfully creates a list containing only 0s and 1s, finds the longest consecutive sequence
of zeros, and displays both its length and the starting and ending indices. It demonstrates the use of lists,
loops, conditional statements, and indexing in Python.

Assignment : 18
Write a program in Python to simulate stack operations using a list (PUSH, POP, PEEP). Also check for
overflow and underflow conditions available in a regular stack.
Source Code :-
stack = []
MAX = 5
while True:
print("\n1. PUSH")
print("2. POP")
print("3. PEEP")
print("4. DISPLAY")
print("5. EXIT")
choice = int(input("Enter your choice: "))
if choice == 1:
if len(stack) == MAX:
print("Stack Overflow")
else:
item = int(input("Enter element: "))
[Link](item)
print(item, "inserted into stack")
elif choice == 2:
if len(stack) == 0:
print("Stack Underflow")
else:
print("Deleted element:", [Link]())
elif choice == 3:
if len(stack) == 0:
print("Stack is empty")
else:
print("Top element:", stack[-1])
elif choice == 4:
if len(stack) == 0:
print("Stack is empty")
else:
print("Stack:", stack)
elif choice == 5:
print("Program Ended")
break
else:
print("Invalid Choice")

Output :-

1. PUSH

10
2. POP
3. PEEP
4. DISPLAY
5. EXIT
Enter your choice: 1
Enter element: 10
10 inserted into stack
Enter your choice: 1
Enter element: 20
20 inserted into stack
Enter your choice: 3
Top element: 20
Enter your choice: 2
Deleted element: 20
Enter your choice: 4
Stack: [10]
Enter your choice: 5
Program Ended

Conclusion :-

The program successfully simulates the basic operations of a stack using a Python list. It performs PUSH, POP,
PEEP, and DISPLAY operations while checking for stack overflow and stack underflow conditions. This
practical demonstrates the implementation of the LIFO (Last In, First Out) principle using lists in Python.

Assignment : 19
Write a program in Python that has a class namely PyWords. It has a field namely process_words that
can store a list of words. The user of the class should pass a list of words as input to the class.
There should be functions to perform the following operations:
(a) words_with_length(1) – Returns a list of all the words of length 1.
(b) starts_with(s) – Returns a list of all the words that start with 's'.
(c) palindromes() – Returns a list of all the palindromes in the list. Report if no palindrome exists in the list.
Source Code :-
class PyWords:
def __init__(self, words):
self.process_words = words
def words_with_length(self, length):
result = []
for word in self.process_words:
if len(word) == length:
[Link](word)

11
return result
def starts_with(self, ch):
result = []
for word in self.process_words:
if [Link](ch):
[Link](word)
return result
def palindromes(self):
result = []
for word in self.process_words:
if word == word[::-1]:
[Link](word)
if len(result) == 0:
return "No palindrome exists."
return result
words = input("Enter words separated by space: ").split()
obj = PyWords(words)
print("Words of length 1:", obj.words_with_length(1))
print("Words starting with 's':", obj.starts_with('s'))
print("Palindromes:", [Link]())

Output :-

Enter words separated by space:


a level madam school sun python eye
Words of length 1: ['a']
Words starting with 's': ['school', 'sun']
Palindromes: ['a', 'level', 'madam', 'eye']

Conclusion :-

The program successfully implements the PyWords class to perform various operations on a list of words. It
identifies words of a specified length, finds words starting with a given letter, and detects palindrome words.
This practical demonstrates the use of classes, objects, methods, lists, loops, string operations, and
user input in Python.

Assignment : 20
Write a recursive function that finds the H.C.F. of two numbers passed as arguments. Then write a
Python program to input a list of integers (intlist[]) and find the H.C.F. of the first and the fifth
elements. The program should handle errors like NameError, IndexError, ZeroDivisionError, and
Source Code :-

def hcf(a, b):


if b == 0:
return a
return hcf(b, a % b)
try:
intlist = []
n = int(input("Enter the number of elements: "))
for i in range(n):
num = int(input("Enter element: "))
[Link](num)
result = hcf(intlist[0], intlist[4])
print("H.C.F. of first and fifth elements =", result)

12
except IndexError:
print("Error: List must contain at least 5 elements.")
except ValueError:
print("Error: Please enter valid integers.")
except ZeroDivisionError:
print("Error: Division by zero occurred.")
except NameError:
print("Error: Variable not defined.")
Output :-

Enter the number of elements: 5


Enter element: 24
Enter element: 18
Enter element: 36
Enter element: 30
Enter element: 60
H.C.F. of first and fifth elements = 12

Conclusion :-

The program successfully finds the H.C.F. (Highest Common Factor) of the first and fifth elements of a list
using a recursive function. It also demonstrates the use of exception handling by managing errors such as
IndexError, ValueError, ZeroDivisionError, and NameError, making the program more reliable and robust.

Assignment : 21
Write a Python function expanding(numlist) that takes as argument a list of integers, numlist[],
and returns True if the absolute difference between each adjacent pair of elements strictly
decreases; otherwise, it returns False. Write a driver program to test the function. The function
should handle necessary validation checks.
Source Code :-
def expanding(numlist):
if len(numlist) < 2:
return False
prev_diff = abs(numlist[1] - numlist[0])
for i in range(2, len(numlist)):
curr_diff = abs(numlist[i] - numlist[i - 1])
if curr_diff >= prev_diff:
return False
prev_diff = curr_diff
return True
try:
n = int(input("Enter number of elements: "))
numlist = []
for i in range(n):
num = int(input("Enter element: "))
[Link](num)
print("Result =", expanding(numlist))
except ValueError:
print("Please enter valid integers.")

Output :-

Enter number of elements: 4


Enter element: 2
Enter element: 10
Enter element: 16
Enter element: 20
Result = True

Conclusion :-

The program successfully checks whether the absolute difference between every pair of adjacent elements in a
list decreases strictly. It uses a user-defined function, loops, conditional statements, and exception handling to
validate the input and determine whether the given list is an expanding list.

Assignment : 22
Write a Python program to print all non-prime, non-Fibonacci numbers within the range a to b,
where a and b are accepted as command-line arguments.
Source Code :-

13
import sys
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int([Link](n)) + 1):
if n % i == 0:
return False
return True
def is_fibonacci(n):
a, b = 0, 1
while b < n:
a, b = b, a + b
return n == 0 or b == n
a = int([Link][1])
b = int([Link][2])
print("Non-prime, Non-Fibonacci Numbers:")
for i in range(a, b + 1):
if (not is_prime(i)) and (not is_fibonacci(i)):
print(i, end=" ")

Output :-

Command:
python [Link] 1 20

Output:
Non-prime, Non-Fibonacci Numbers:
4 6 8 9 10 12 14 15 16 18 20

Conclusion :-

The program successfully prints all non-prime and non-Fibonacci numbers within the specified range using
command-line arguments. It demonstrates the use of functions, loops, conditional statements, command-
line arguments, and mathematical logic in Python.

Assignment : 23
Write a Python program to perform matrix addition, matrix subtraction, and matrix multiplication
by simulating matrices as lists of lists. You may use separate functions for each operation.

Source Code :-
def add_matrix(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
[Link](A[i][j] + B[i][j])
[Link](row)
return result
def subtract_matrix(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
[Link](A[i][j] - B[i][j])
[Link](row)
return result
def multiply_matrix(A, B):
result = []

14
for i in range(len(A)):
row = []
for j in range(len(B[0])):
sum = 0
for k in range(len(B)):
sum += A[i][k] * B[k][j]
[Link](sum)
[Link](row)
return result
A = [[1, 2],
[3, 4]]
B = [[5, 6],
[7, 8]]
print("Matrix A:")
for row in A:
print(row)
print("\nMatrix B:")
for row in B:
print(row)
print("\nAddition:")
for row in add_matrix(A, B):
print(row)
print("\nSubtraction:")
for row in subtract_matrix(A, B):
print(row)
print("\nMultiplication:")
for row in multiply_matrix(A, B):
print(row)
Output :-
Matrix A:
[1, 2]
[3, 4]
Matrix B:
[5, 6]
[7, 8]
Addition:
[6, 8]
[10, 12]
Subtraction:
[-4, -4]
[-4, -4]
Multiplication:
[19, 22]
[43, 50]
Conclusion :-

The program successfully performs matrix addition, matrix subtraction, and matrix multiplication using
matrices represented as lists of lists. It demonstrates the use of functions, nested loops, lists, and
arithmetic operations in Python for implementing basic matrix operations.

Assignment : 24
Write a Python program to implement a queue using a list. The program must
incorporate the functions add_element(), delete_element(), list_full(), and
list_empty().
Source Code
MAX = 5
queue = []
def list_full():
return len(queue) == MAX
def list_empty():
return len(queue) == 0
def add_element(item):
if list_full():
print("Queue is Full")
else:
[Link](item)
print(item, "inserted into Queue")
def delete_element():
if list_empty():
print("Queue is Empty")
else:
print("Deleted Element:", [Link](0))
while True:

15
print("\n1. Add Element")
print("2. Delete Element")
print("3. Display Queue")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
item = int(input("Enter element: "))
add_element(item)
elif choice == 2:
delete_element()
elif choice == 3:
print("Queue =", queue)
elif choice == 4:
print("Program Ended")
break
else:
print("Invalid Choice")

Output :-

1. Add Element
2. Delete Element
3. Display Queue
4. Exit
Enter your choice: 1
Enter element: 10
10 inserted into Queue
Enter your choice: 1
Enter element: 20
20 inserted into Queue
Enter your choice: 3
Queue = [10, 20]
Enter your choice: 2
Deleted Element: 10
Enter your choice: 3
Queue = [20]
Enter your choice: 4
Program Ended

Conclusion :-

The program successfully implements a Queue using a Python list. It performs the basic queue operations such
as adding an element, deleting an element, and checking whether the queue is full or empty. It
demonstrates the FIFO (First In, First Out) principle using lists and user-defined functions in Python.

Assignment : 25
Given a string, write a program in Python to find the occurrences of every character, number,
special character, and punctuation mark.
Source Code :-
string = input("Enter a string: ")
letters = 0
digits = 0
special = 0
for ch in string:
if [Link]():
letters += 1
elif [Link]():
digits += 1
else:
special += 1
print("Number of Alphabets =", letters)
print("Number of Digits =", digits)
print("Number of Special Characters =", special)
print("\nOccurrence of each character:")
count = {}
for ch in string:
if ch in count:
count[ch] += 1
else:

16
count[ch] = 1
for key in count:
print(key, ":", count[key])

Output :-

Enter a string: Python123@#


Number of Alphabets = 6
Number of Digits = 3
Number of Special Characters = 2
Occurrence of each character:
P : 1
y : 1
t : 1
h : 1
o : 1
n : 1
1 : 1
2 : 1
3 : 1
@ : 1
# : 1

Conclusion :-

The program successfully counts the number of alphabets, digits, and special characters in a given string.
It also displays the occurrence of each character using a dictionary. This practical demonstrates the use of
strings, dictionaries, loops, conditional statements, and built-in string methods in Python.

Assignment : 26
Develop
Write a Python
a Python program program that
that accepts reads marks from
a hyphen-separated three
sequence different
of words subjects
as input and
and prints
calculates their average.
the words in a hyphen-separated sequence after sorting them alphabetically.
Sample Input: green-red-yellow-black-white
Expected Output: black-green-red-white-yellow

Source Code :-
words = input("Enter hyphen-separated words: ")
word_list = [Link]("-")
word_list.sort()
result = "-".join(word_list)
print("Sorted words:", result)

Output :-

Enter hyphen-separated words: green-red-yellow-black-white


Sorted words: black-green-red-white-yellow

Conclusion :-

The program successfully accepts a hyphen-separated sequence of words, sorts them in


alphabetical order, and displays the sorted sequence using hyphens. It demonstrates the use of
string methods (split() and join()), list sorting (sort()), and user input in Python.

17
Assignment : 27
Develop
Write a Python
a Python program program
to print thethat reads
following marks
pattern (forfrom three
n = 3). different subjects and
calculates their average.

Source Code :-
n = 3
for i in range(n):
for j in range(n - i - 1):
print(" ", end="")
print("*", end="")
for j in range(2 * i - 1):
print(" ", end="")
if i > 0:
print("*", end="")
print()
for i in range(n - 2, -1, -1):
for j in range(n - i - 1):
print(" ", end="")
print("*", end="")
for j in range(2 * i - 1):
print(" ", end="")
if i > 0:
print("*", end="")
print()

Output :-

*
* *
* *
* *
*

Conclusion :-

The program successfully prints the required star pattern using nested for loops. It demonstrates
the use of nested loops, spaces, and pattern printing techniques in Python.

Assignment : 28
Develop
Write a Python
a Python program program that reads
to check whether a givenmarks
numberfrom three different
is an Armstrong number. subjects and
calculates their average.

Source Code :-
num = int(input("Enter a number: "))
temp = num
digits = len(str(num))
sum = 0
while temp > 0:
digit = temp % 10
sum = sum + digit ** digits
temp = temp // 10
if sum == num:
print(num, "is an Armstrong Number")
else:
print(num, "is not an Armstrong Number")

Output :-

Enter a number: 153


153 is an Armstrong Number

Conclusion :-

The program successfully checks whether a given number is an Armstrong number by


calculating the sum of each digit raised to the power of the total number of digits. It demonstrates
the use of loops, arithmetic operations, conditional statements, and user input in Python.

18
Assignment : 29
Develop
Write a Python
a Python program program that reads
to find the power marks
of a number from
(i.e. three
) using different
recursion. subjects and
calculates their average.

Source Code :-
def power(n, p):
if p == 0:
return 1
return n * power(n, p - 1)
num = int(input("Enter the number: "))
exp = int(input("Enter the power: "))
result = power(num, exp)
print("Result =", result)

Output :-

Enter the number: 2


Enter the power: 5
Result = 32

Conclusion :-

The program successfully calculates the power of a number using a recursive function. It
demonstrates the concept of recursion by repeatedly multiplying the base number until the
exponent becomes zero.

Assignment : 30
Problem Statement
Write a program to create a function show_employee using the following condition:
Develop a Python program that reads marks from three different
It should accept the employee's name and salary and display both.
subjects and
calculates their average.

Source Code :-
def show_employee(name, salary):
print("Employee Name :", name)
print("Employee Salary :", salary)
name = input("Enter Employee Name: ")
salary = float(input("Enter Employee Salary: "))
show_employee(name, salary)

Output :-

Enter Employee Name: Rahul


Enter Employee Salary: 35000
Employee Name : Rahul
Employee Salary : 35000.0

Conclusion :-

The program successfully accepts an employee's name and salary through a user-defined function
and displays the details. It demonstrates the use of functions, function parameters, user
input, and output statements in Python.

Assignment : 31
Problem Statement
Develop
Write a Python
a Python program program that
to count even reads
and marksinfrom
odd numbers a [Link] different subjects and
calculates their average.
Source Code :-
# Program to count even and odd numbers in a list

numbers = []

n = int(input("Enter the number of elements: "))

for i in range(n):
num = int(input("Enter element: "))
[Link](num)

19
even = 0
odd = 0

for num in numbers:


if num % 2 == 0:
even += 1
else:
odd += 1

print("List =", numbers)


print("Even Numbers =", even)
print("Odd Numbers =", odd)

Output :-

Enter the number of elements: 6


Enter element: 10
Enter element: 15
Enter element: 20
Enter element: 7
Enter element: 8
Enter element: 13
List = [10, 15, 20, 7, 8, 13]
Even Numbers = 3
Odd Numbers = 3

Conclusion :-

The program successfully counts the number of even and odd elements in a list entered by the
user. It demonstrates the use of lists, loops, conditional statements, and the modulus (%)
operator in Python.

Assignment : 32
Problem Statement
Develop
Write a Python
a Python function program that reads
to find the length marks
of a given from
string. three different subjects and
calculates their average.
Source Code :-
def string_length(text):
count = 0
for ch in text:
count += 1
return count
string = input("Enter a string: ")
print("Length of the string =", string_length(string))

Output :-

Enter a string: Python Programming


Length of the string = 18

Conclusion :-

The program successfully calculates the length of a given string using a user-defined function
without using the built-in len() function. It demonstrates the use of functions, loops, variables,
and string traversal in Python.

Assignment : 33
Problem Statement
Develop
Write a Python
a Python program program
to calculatethat reads
the GCD andmarks from
LCM of two three
numbers. different subjects and
calculates their average.
Source Code :-
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
a = num1
b = num2
while b != 0:
a, b = b, a % b
gcd = a

20
lcm = (num1 * num2) // gcd
print("GCD =", gcd)
print("LCM =", lcm)

Output :-

Enter first number: 12


Enter second number: 18
GCD = 6
LCM = 36

Conclusion :-

The program successfully calculates the Greatest Common Divisor (GCD) and Least Common
Multiple (LCM) of two numbers. It demonstrates the use of the Euclidean algorithm, arithmetic
operations, and user input in Python.

Assignment : 34
Problem Statement
Develop
Write a Python
a Python program program
to create a that reads
lambda marks
function from15three
that adds different
to a given numbersubjects
passed in and
as
ancalculates
argument. their average.

Source Code :-
add15 = lambda x: x + 15
num = int(input("Enter a number: "))
print("Result =", add15(num))

Output :-

Enter a number: 25
Result = 40

Conclusion :-

The program successfully creates and uses a lambda function to add 15 to a given number. It
demonstrates the use of anonymous functions, function arguments, and user input in Python.

Assignment : 35
Problem Statement
Develop a Python program that reads marks from three different subjects and
Write a Python program to implement binary search.
calculates their average.
Source Code :-
numbers = [10, 20, 30, 40, 50, 60, 70]
key = int(input("Enter the element to search: "))
low = 0
high = len(numbers) - 1
found = False
while low <= high:
mid = (low + high) // 2
if numbers[mid] == key:
print("Element found at position", mid + 1)
found = True
break
elif numbers[mid] < key:
low = mid + 1
else:
high = mid - 1
if not found:
print("Element not found")

Output :-

Enter the element to search: 50


Element found at position 5

Conclusion :-
The program successfully implements the Binary Search algorithm to search for an element in a
sorted list. It repeatedly divides the search range into two halves, making the search process

21
efficient. This practical demonstrates the use of lists, loops, conditional statements, and
searching algorithms in Python.

Assignment : 36
Problem Statement
Develop
Write a Python
a Python program program that
to implement reads to
Quicksort marks
sort a from three different
list of numbers. subjects and
calculates their average.
Source Code :-
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = []
right = []
for i in arr[1:]:
if i <= pivot:
[Link](i)
else:
[Link](i)
return quicksort(left) + [pivot] + quicksort(right)
numbers = []
n = int(input("Enter the number of elements: "))
for i in range(n):
num = int(input("Enter element: "))
[Link](num)
print("Original List =", numbers)
sorted_list = quicksort(numbers)
print("Sorted List =", sorted_list)

Output :-

Enter the number of elements: 6


Enter element: 45
Enter element: 12
Enter element: 78
Enter element: 23
Enter element: 56
Enter element: 10
Original List = [45, 12, 78, 23, 56, 10]
Sorted List = [10, 12, 23, 45, 56, 78]

Conclusion :-

The program successfully implements the Quick Sort algorithm to sort a list of numbers in
ascending order. It uses the divide-and-conquer approach by selecting a pivot element,
partitioning the list, and recursively sorting the sublists. This practical demonstrates the use of
recursion, lists, loops, and sorting algorithms in Python.

Assignment : 37
Problem Statement
Develop
Write a Python
a Python program program that
to accept two filereads
names marks from three
as command-line different
arguments wheresubjects and
one of them
iscalculates
a source file their average.
containing some lines of text and the other is a blank text file. Copy the contents of
the source file into the destination file by adding the number of vowels in each line at the end of
that line. Report if the source file is blank or not found.

Source Code :-
import sys
try:
source = [Link][1]
destination = [Link][2]
with open(source, "r") as f:
lines = [Link]()
if len(lines) == 0:
print("Source file is blank.")
else:
with open(destination, "w") as out:
for line in lines:
count = 0
for ch in [Link]():
if ch in "aeiou":
count += 1

22
[Link]([Link]() + " Vowels = " + str(count) + "\n")
print("File copied successfully.")
except FileNotFoundError:
print("Source file not found.")

Output :-

Command:
python [Link] [Link] [Link]
Source File ([Link]):
Python is easy
Programming Lab
Destination File ([Link]):
Python is easy Vowels = 4
Programming Lab Vowels = 4
File copied successfully.

Conclusion :-

The program successfully accepts the source and destination file names through command-line
arguments, copies the contents of the source file to the destination file, appends the number of
vowels present in each line, and handles cases where the source file is blank or not found using
exception handling.

Assignment : 38
Problem Statement
Develop
Write a Python
a Python program
class to perform that and
addition reads marks from
multiplication three
of two different
complex number subjects
objects. and
calculates their average.
Source Code :-
class Complex:
def __init__(self, real, imag):
[Link] = real
[Link] = imag
def add(self, other):
return Complex([Link] + [Link],
[Link] + [Link])
def multiply(self, other):
real = [Link] * [Link] - [Link] * [Link]
imag = [Link] * [Link] + [Link] * [Link]
return Complex(real, imag)
def display(self):
print([Link], "+", [Link], "i")
c1 = Complex(2, 3)
c2 = Complex(4, 5)
print("First Complex Number:")
[Link]()
print("Second Complex Number:")
[Link]()
print("\nAddition:")
result1 = [Link](c2)
[Link]()
print("\nMultiplication:")
result2 = [Link](c2)
[Link]()

Output :-

First Complex Number:


2 + 3 i
Second Complex Number:
4 + 5 i
Addition:
6 + 8 i
Multiplication:
-7 + 22 i

Conclusion :-

The program successfully performs addition and multiplication of two complex numbers using a
Python class. It demonstrates the use of classes, objects, constructors, methods, and
arithmetic operations in Python while implementing basic operations on complex numbers.

23
Assignment : 39
Problem Statement
Develop
Write a Pythona Python
dictionary program
that storesthat readsand
full name marks
CGPA from threeofdifferent
information subjects
10 final-year [Link]
calculates
Then their
perform the average.
following operations:
(a) Print the names as initials with surname (e.g., Arindam Biswas → A. Biswas).
(b) Display the details of the student with the highest CGPA.
(c) Display the names of students with CGPA below 3.0 (out of 10.0), if any.

Source Code :-
students = {
"Arindam Biswas": 8.7,
"Rahul Das": 7.8,
"Priya Sen": 9.2,
"Sourav Roy": 6.9,
"Ananya Ghosh": 8.5,
"Riya Paul": 2.8,
"Amit Dey": 7.2,
"Sneha Mitra": 9.0,
"Rohan Pal": 2.5,
"Ankit Sharma": 8.1
}
print("Names as Initials:")
for name in students:
parts = [Link]()
print(parts[0][0] + ".", parts[1])
highest = max(students, key=[Link])
print("\nStudent with Highest CGPA:")
print("Name :", highest)
print("CGPA :", students[highest])
print("\nStudents with CGPA below 3.0:")
found = False
for name, cgpa in [Link]():
if cgpa < 3.0:
print(name, "-", cgpa)
found = True
if not found:
print("No student found.")

Output :-

Names as Initials:
A. Biswas
R. Das
P. Sen
S. Roy
A. Ghosh
R. Paul
A. Dey
S. Mitra
R. Pal
A. Sharma
Student with Highest CGPA:
Name : Priya Sen
CGPA : 9.2
Students with CGPA below 3.0:
Riya Paul - 2.8
Rohan Pal - 2.5

Conclusion :-

The program successfully stores the names and CGPA of students in a dictionary. It prints the
names in initials with surname format, identifies the student with the highest CGPA, and
displays the names of students whose CGPA is below 3.0. It demonstrates the use of
dictionaries, loops, string manipulation, conditional statements, and built-in functions in
Python.

Assignment : 40
Problem Statement
Develop
Write a Python
a Python program program
to create a that readsvalues
list (taking marks from
from three
the user) different
and count thesubjects
occurrenceand
of
calculates their average.
each element. Then create a dictionary to show the count of each element.
Example:

24
Input: sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
Output: {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}

Source Code :-
numbers = []
n = int(input("Enter the number of elements: "))
for i in range(n):
num = int(input("Enter element: "))
[Link](num)
count = {}
for num in numbers:
if num in count:
count[num] += 1
else:
count[num] = 1
print("Dictionary of occurrences:")
print(count)

Output :-

Enter the number of elements: 9


Enter element: 11
Enter element: 45
Enter element: 8
Enter element: 11
Enter element: 23
Enter element: 45
Enter element: 23
Enter element: 45
Enter element: 89
Dictionary of occurrences:
{11: 2, 45: 3, 8: 1, 23: 2, 89: 1}

Conclusion :-

The program successfully creates a list from user input, counts the occurrence of each element,
and stores the result in a dictionary. It demonstrates the use of lists, dictionaries, loops,
conditional statements, and user input in Python.
Assignment : 41
Problem Statement
Develop
Write a Python
a program program
in Python that areads
to implement marks
function from three
that reverses different
the elements of a subjects
nested list and
calculates
recursively. their average.
Example:
Input: [[1, 2], [3, [4, 5]], 6]
Output: [6, [[5, 4], 3], [2, 1]]

Source Code :-
def reverse_nested(lst):
result = []
for item in lst[::-1]:
if isinstance(item, list):
[Link](reverse_nested(item))
else:
[Link](item)
return result
nested_list = [[1, 2], [3, [4, 5]], 6]
print("Original List:")
print(nested_list)
print("\nReversed Nested List:")
print(reverse_nested(nested_list))

Output :-

Original List:
[[1, 2], [3, [4, 5]], 6]
Reversed Nested List:
[6, [[5, 4], 3], [2, 1]]

Conclusion :-

25
The program successfully reverses a nested list recursively, including all inner lists. It demonstrates
the use of recursion, lists, conditional statements, and the isinstance() function to
process nested data structures in Python.
Assignment : 42
Problem Statement
Develop
Write a Python
a Python program program that reads
to take a multi-word marks
string from
from the three
user. Then different
perform thesubjects
following and
calculates
operations: their average.
(a) Count the occurrences of a given word in the given string.
(b) Form a string where the first character and the last character have been exchanged.

Source Code :-
string = input("Enter a string: ")
word = input("Enter the word to search: ")
words = [Link]()
count = 0
for w in words:
if w == word:
count += 1
print("Count of the word is:", count)
if len(string) > 1:
modified = string[-1] + string[1:-1] + string[0]
else:
modified = string
print("Modified string:", modified)

Output :-

Enter a string: orange is orange in colour


Enter the word to search: orange
Count of the word is: 2
Modified string: erange is orange in colouro

Conclusion :-

The program successfully accepts a multi-word string from the user, counts the occurrences of a
specified word, and creates a new string by exchanging its first and last characters. It
demonstrates the use of strings, loops, conditional statements, string slicing, and user
input in Python.

Assignment : 43
Problem Statement
Develop
Write a Python
a Python program program that reads
to find the power marks
of a number from
using three
recursion. different subjects and
calculates their average.
Source Code :-
def power(base, exp):
if exp == 0:
return 1
return base * power(base, exp - 1)
base = int(input("Enter base: "))
exp = int(input("Enter exponential value: "))
result = power(base, exp)
print("Result:", result)

Output :-

Enter base: 2
Enter exponential value: 5
Result: 32

Conclusion :-

The program successfully calculates the power of a number using a recursive function. It
demonstrates the concept of recursion, function calls, and user input in Python.

Assignment : 44
Problem Statement
Develop
Write a Python
a Python program program
to calculatethat readsseries:
the cosine marks from three different subjects and
calculates their average.

26
\cos x = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots
where x is given in degrees and the number of terms is entered by the user.

Source Code :-
import math
x = float(input("Enter the value of x in degrees: "))
n = int(input("Enter the number of terms: "))
x = [Link](x)
cosx = 0
for i in range(n):
term = ((-1) ** i) * (x ** (2 * i)) / [Link](2 * i)
cosx += term
print("cos(x) =", cosx)

Output :-

Enter the value of x in degrees: 0


Enter the number of terms: 10
cos(x) = 1.0

Conclusion :-

The program successfully calculates the value of cos(x) using its mathematical series
expansion. It demonstrates the use of loops, factorials, exponentiation, the math
module, and series computation in Python.

Assignment : 45
Problem Statement
Develop
Write a Python
a Python program program thatareads
to test whether string Smarks from
comprising three different
lowercase characterssubjects
is a and
calculates
Heterogram or their average.
not. The string should be passed as a command-line argument.
Note: A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once.
Examples:
"the big dwarf jumps" → Heterogram
"the sun rises in the east" → Not a Heterogram

Source Code
import sys
s = [Link][1].lower()
letters = []
is_heterogram = True
for ch in s:
if [Link]():
if ch in letters:
is_heterogram = False
break
else:
[Link](ch)
if is_heterogram:
print("The given string is a Heterogram.")
else:
print("The given string is not a Heterogram.")

Output :-

Command:
python [Link] "the big dwarf jumps"

Output:
The given string is a Heterogram.
Another Example
Command:
python [Link] "the sun rises in the east"

Output:
The given string is not a Heterogram.

Conclusion :-

27
The program successfully checks whether a given string is a Heterogram by ensuring that no
alphabet appears more than once. It accepts the string as a command-line argument and
demonstrates the use of command-line arguments, loops, lists, conditional statements,
and string methods in Python.

Assignment : 46
Problem Statement
Develop
Write a Python
a Python program program thatthe
that calculates reads marks
percentage offrom three
leap years different
over the total subjects
number of and
calculates their average.
years within a user-input range.
Example:
Lower Range = 2018
Upper Range = 2022
Leap Years = 1 (2020)
Total Years = 5
Percentage = (1/5) × 100 = 20%

Source Code :-
lower = int(input("Enter the lower range: "))
upper = int(input("Enter the upper range: "))
leap = 0
total = upper - lower + 1
for year in range(lower, upper + 1):
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
leap += 1
percentage = (leap / total) * 100
print("Number of Leap Years =", leap)
print("Total Years =", total)
print("Percentage of Leap Years = {:.2f}%".format(percentage))

Output :-

Enter the lower range: 2018


Enter the upper range: 2022
Number of Leap Years = 1
Total Years = 5
Percentage of Leap Years = 20.00%

Conclusion :-

The program successfully counts the number of leap years within the given range and calculates
their percentage with respect to the total number of years. It demonstrates the use of loops,
conditional statements, arithmetic operations, and user input in Python.

Assignment : 47
Problem Statement
Develop
Write a Pythona Python
program program that
to accept two reads as
filenames marks fromRead
user input. three different
each subjects
line of the and
first file, sort
calculates
the words in eachtheir
lineaverage.
alphabetically, and copy the sorted content to the second file. Report if the
source file is blank.
Example:
Input File Content:
Welcome
to you in
this planet called earth
Output File Content:
Welcome
in to you
called earth planet this

Source Code :-
source = input("Enter source file name: ")
destination = input("Enter destination file name: ")
try:
with open(source, "r") as file:
lines = [Link]()
if len(lines) == 0:
print("Source file is blank.")
else:
with open(destination, "w") as out:
for line in lines:

28
words = [Link]().split()
[Link]()
[Link](" ".join(words) + "\n")
print("Contents copied successfully.")
except FileNotFoundError:
print("Source file not found.")

Output :-

Enter source file name: [Link]


Enter destination file name: [Link]
Contents copied successfully.
Output File ([Link]):
Welcome
in to you
called earth planet this

Conclusion :-
The program successfully reads the contents of a source file, sorts the words in each line
alphabetically, and writes the sorted lines to another file. It also checks whether the source file is
blank or missing. This practical demonstrates the use of file handling, lists, sorting, exception
handling, and string operations in Python.

Assignment : 48
Pro blem Statement
Develop a Python program that reads marks from three different subjects and
Write a Python program that takes a list of words from the command-line argument and returns
calculates
the their
smallest and average.
the longest words along with the length of each word.

Source Code :-
import sys
words = [Link][1:]
smallest = words[0]
longest = words[0]
for word in words:
if len(word) < len(smallest):
smallest = word
if len(word) > len(longest):
longest = word
print("Smallest Word :", smallest)
print("Length :", len(smallest))
print("Longest Word :", longest)
print("Length :", len(longest))

Output :-

Command:
python [Link] apple banana cat elephant dog

Output:
Smallest Word : cat
Length : 3
Longest Word : elephant
Length : 8

Conclusion :-

The program successfully accepts a list of words through command-line arguments and
identifies the smallest and longest words along with their lengths. It demonstrates the use of
command-line arguments, loops, string length calculation, conditional statements, and
built-in functions in Python.

Assignment : 49
Problem Statement
Develop
Write a Python
a Python program program that
to search for reads
numbers marks
(0–9) from
of length three 1different
between and 3 in a subjects and
given string.
calculates their average.
The numbers in the string are separated by commas (,).

Source Code :-
string = input("Enter the string: ")
numbers = [Link](",")

29
print("Numbers having length between 1 and 3:")
for num in numbers:
num = [Link]()
if [Link]() and 1 <= len(num) <= 3:
print(num)

Output :-

Enter the string:


12,4567,8,123,9999,45,7,1000
Numbers having length between 1 and 3:
12
8
123
45
7
Conclusion :-

The program successfully extracts numbers separated by commas and displays only those whose
length is between 1 and 3 digits. It demonstrates the use of string methods (split(), strip(),
isdigit()), loops, conditional statements, and user input in Python.

Assignment : 50
Problem Statement
Develop
Write a Python a Python
program program that
to create two reads marks from three different subjects
lists: and
L1calculates their
= ['a', 'b', 'c', average.
'd', 'f']
L2 = [1000, 200, 300, 400, 500]
Convert them into a dictionary such that each item from L1 becomes the key and the
corresponding item from L2 becomes the value. Then perform the following operations:
(a) Check if the value 200 exists in the dictionary.
(b) Rename the key 'f' to 'e'.
(c) Get the key corresponding to the minimum value in the dictionary.

Source Code :-
L1 = ['a', 'b', 'c', 'd', 'f']
L2 = [1000, 200, 300, 400, 500]
d = dict(zip(L1, L2))
print("Dictionary =", d)
if 200 in [Link]():
print("200 exists in the dictionary.")
else:
print("200 does not exist.")
d['e'] = [Link]('f')
print("Dictionary after renaming key:", d)
min_key = min(d, key=[Link])
print("Key with minimum value:", min_key)

Output :-

Dictionary = {'a': 1000, 'b': 200, 'c': 300, 'd': 400, 'f': 500}
200 exists in the dictionary.
Dictionary after renaming key:
{'a': 1000, 'b': 200, 'c': 300, 'd': 400, 'e': 500}
Key with minimum value: b

Conclusion :-

The program successfully creates a dictionary from two lists and performs the required operations:
checking for the existence of a value, renaming a key, and finding the key associated with the
minimum value. It demonstrates the use of lists, dictionaries, the zip() function, dictionary
methods, conditional statements, and built-in functions in Python.

Assignment : 51
Problem Statement
Develop
Write a Python
a Python program program that
to slice a list reads
(taken marks
as input fromfrom three
the user) intodifferent subjects
three equal and
chunks and
calculates
then their
reverse each average.
chunk. Input the list such that the number of elements is divisible by 3.
Example:
Input: sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]
Output:
Chunk 1 → [11, 45, 8] → [8, 45, 11]

30
Chunk 2 → [23, 14, 12] → [12, 14, 23]
Chunk 3 → [78, 45, 89] → [89, 45, 78]

Source Code :-
numbers = []
n = int(input("Enter the number of elements (multiple of 3): "))
for i in range(n):
num = int(input("Enter element: "))
[Link](num)
if n % 3 != 0:
print("Number of elements must be divisible by 3.")
else:
size = n // 3
for i in range(3):
chunk = numbers[i * size:(i + 1) * size]
print("Chunk", i + 1, "=", chunk)
print("After reversing =", chunk[::-1])

Output :-

Enter the number of elements (multiple of 3): 9


Enter element: 11
Enter element: 45
Enter element: 8
Enter element: 23
Enter element: 14
Enter element: 12
Enter element: 78
Enter element: 45
Enter element: 89
Chunk 1 = [11, 45, 8]
After reversing = [8, 45, 11]
Chunk 2 = [23, 14, 12]
After reversing = [12, 14, 23]
Chunk 3 = [78, 45, 89]
After reversing = [89, 45, 78]

Conclusion :-

The program successfully divides the input list into three equal chunks and reverses each chunk
individually. It demonstrates the use of lists, slicing, loops, conditional statements, and user
input in Python.

Assignment : 52
Problem Statement
A Develop a Python
website requires usersprogram that reads
to input a username andmarks from
password three different
for registration. subjects
Write a Python and
calculates their average.
program to check the validity of the password according to the following criteria:
At least 1 lowercase letter (a-z)
At least 1 uppercase letter (A-Z)
At least 1 digit (0-9)
At least 1 special character from $ # @
Minimum password length: 6
Maximum password length: 12
The program should accept a sequence of comma-separated passwords and print only the valid
passwords.
Example:
Input: ABd1234@1,Af1#,2w3E*,2We3345
Output: ABd1234@1

Source Code :-
passwords = input("Enter comma-separated passwords: ").split(",")
valid_passwords = []
for password in passwords:
if len(password) < 6 or len(password) > 12:
continue
has_lower = False
has_upper = False
has_digit = False
has_special = False
for ch in password:
if [Link]():

31
has_lower = True
elif [Link]():
has_upper = True
elif [Link]():
has_digit = True
elif ch in "$#@":
has_special = True
if has_lower and has_upper and has_digit and has_special:
valid_passwords.append(password)
print("Valid Password(s):")
print(",".join(valid_passwords))

Output :-

Enter comma-separated passwords:


ABd1234@1,Af1#,2w3E*,2We3345
Valid Password(s):
ABd1234@1

Conclusion :-

The program successfully validates user passwords based on the given criteria and displays only
the valid passwords. It demonstrates the use of strings, loops, conditional statements, lists,
string methods, and user input in Python.

32

You might also like