PP LAB MANUAL 2nd Sem
PP LAB MANUAL 2nd Sem
Output Format:
The output is a string.
PROGRAM
str=input("Enter a String: ")
print(str)
OUTPUT:
Test case
Debug
Expected output Actual output
Enter·a·String:·CodeTantra Tech Enter·a·String:·CodeTantra Tech
Solutions Solutions
CodeTantra·Tech·Solutions⏎ CodeTantra·Tech·Solutions⏎
b) Write a Python program to read integer, float, and string values and
display them.
EXPLANATION
Input Format:
1
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
• The three output lines contain integer, float, and string values.
PROGRAM
n1=int(input(""))
n2=float(input(""))
str=input("")
print(n1)
print(n2)
print(str)
Test case
Debug
Expected output Actual output
12345 12345
123.45678 123.45678
CodeTantra CodeTantra
12345⏎ 12345⏎
123.45678⏎ 123.45678⏎
CodeTantra⏎ CodeTantra⏎
2
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Formula:
C = (F - 32) * 5/9
Input format:
The input is the floating point value that represents the temperature in
Fahrenheit.
Output format:
The output is the floating point value that represents the temperature in Celsius.
PROGRAM:
F=float(input(""))
C=(F-32)*5/9
print(round(C,3))
Test case
Debug
Expected output Actual output
40 40
4.444 4.444
3
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Debug
Expected output Actual output
Base:·10 Base:·10
Height:·15 Height:·15
Area:·75.00⏎ Area:·75.00⏎
c) Write a python program to read the marks in 4 subjects and display the
average.
EXPLANATION:
Input format:
The first 4 lines reads integers that represents marks for 4 subjects.
4
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output format:
The output is float value that represents average.
PROGRAM
m1=float(input(""))
m2=float(input(""))
m3=float(input(""))
m4=float(input(""))
average=(m1+m2+m3+m4)/4
print(average)
Test case
Debug
Expected output Actual output
23 23
32 32
45 45
65 65
41.25⏎ 41.25⏎
5
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
EXPLANATION
Input format:
The first 2 lines reads integers.
Output format:
The output line contains boolean values which represent the results of various
comparisons operations ==, !=, <, <=, >, >= and the format should be like
below:
{num1} (boolean condition) {num2} : boolean value respectively
PROGRAM
num1=int(input())
num2=int(input())
print(f"{num1} == {num2} : {num1==num2}" )
print(f"{num1} != {num2} : {num1 !=num2}")
print(f"{num1} < {num2} : {num1 <num2}")
print(f"{num1} <= {num2} : {num1 <=num2}")
print(f"{num1} > {num2} : {num1 >num2}")
print(f"{num1} >= {num2} : {num1 >=num2}")
Test case
Debug
6
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
b) Take two strings as input from the console using input() function. Write
a program using membership operators to check whether the given second
string is present in the first string or not. Print the result of the two input
strings to the console, as shown in the example.
EXPLANATION
Sample Input and Output1:
str1: Hello World Welcome To Python Programming
str2: Pro
Pro in Hello World Welcome To Python Programming: True
7
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
EXPLANATION
Similarly Take two floating point numbers x and y as input from the console
using input() function. For each identity operator is and is not, print to the
console, the result of the two float numbers as shown in the example.
PROGRAM:
= int(input("Enter an integer: "))
y = int(input("Enter the same integer: "))
8
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Debug
Expected output Actual output
Enter·an·integer:·20 Enter·an·integer:·20
Enter·the·same·integer:·20 Enter·the·same·integer:·20
x·is·y·True⏎ x·is·y·True⏎
x·is·not·y·False⏎ x·is·not·y·False⏎
Enter·a·Float·Number:·2.3 Enter·a·Float·Number:·2.3
Enter·the·same·Number:·2.3 Enter·the·same·Number:·2.3
x·is·y·False⏎ x·is·y·False⏎
x·is·not·y·True⏎ x·is·not·y·True⏎
d) Take two integers x and y as inputs from the console using input()
function. For each bitwise operator ( >> , <<, &, |, ~, and ^ ), print to the
console, the result of applying these operators on the two input integers as
shown in the example.
EXPLANATION
Sample Input and Output:
x: 52
y: 20
52 >> 20 is 0
52 << 20 is 54525952
9
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
52 & 20 is 20
52 | 20 is 52
~ 52 is -53
52 ^ 20 is 32
PROGRAM
x=int(input("x: "))
y=int(input("y: "))
print(x,">>",y ,"is" ,x>>y)
print(x,"<<",y ,"is" ,x<<y)
print(x,"&",y ,"is" ,x&y)
print(x,"|",y ,"is" ,x|y)
print("~",x,"is",~x)
print(x,"^",y ,"is" ,x^y)
Test case
Expected output Actual output
x:·30 x:·30
y:·2 y:·2
30·>>·2·is·7⏎ 30·>>·2·is·7⏎
30·<<·2·is·120⏎ 30·<<·2·is·120⏎
30·&·2·is·2⏎ 30·&·2·is·2⏎
30·|·2·is·30⏎ 30·|·2·is·30⏎
~·30·is·-31⏎ ~·30·is·-31⏎
30·^·2·is·28⏎ 30·^·2·is·28⏎
10
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Input Format:
Prompt the user to enter a floating-point number
Output Format:
Print "{number} is positive" if the number is positive, else print "{number} is
negative" and if it is zero print "The number is zero".
PROGRAM
num=float(input(""))
if num<0:
print(f"{num} is negative")
elif num>0:
print(f"{num} is positive")
else:
print("The number is zero")
Test case
Debug
Expected output Actual output
2 2
2.0·is·positive⏎ 2.0·is·positive⏎
11
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
EXPLANATION
Note: use split() function to separate user given data based on ','.
PROGRAM:
n=input("a,b,c: ")
t=n.split(",")
a=int(t[0])
b=int(t[1])
c=int(t[2])
Test case
12
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
c) Write a Python program that prompts user to take two integers a,b and
swap them
EXPLANATION
Input Format:
• The input contains two integers a,b each on a new line respectively.
Output Format:
• It prints the values of a and b after swapping them.
PROGRAM
a=int(input(""))
b=int(input(""))
temp=a
a=b
b=temp
print(f"After swapping: a = {a}, b = {b}")
Test case
13
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
print("Electricity Bill")
print("Customer ID:", customer_id)
print("Customer Name:", customer_name)
print("Units Consumed:", units)
print("Amount: Rs. {:.2f}".format(amount))
print("Surcharge (20%): Rs. {:.2f}".format(surcharge_amount))
print("Total Amount: Rs. {:.2f}".format(total_amount))
Maximum time
0.007 s
7.00 ms
2 out of 2 shown test case(s) passed
2 out of 2 hidden test case(s) passed
15
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Output Format:
Print the reversed integer.
PROGRAM
number=int(input("Enter a number :"))
revs_number=0
16
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Debug
Expected output Actual output
Enter·a·number·:1485 Enter·a·number·:1485
Reverse·of·a·number·:·5841⏎ Reverse·of·a·number·:·5841⏎
Requirements:
• Write a Python program that reads a non-negative integer from the user
and calculates its factorial.
• The factorial of a number n (denoted as n!) is the product of all positive
integers less than or equal to n.
• By definition, the factorial of 0 is 1.
Input Format:
The first line contains a non-negative integer n.
17
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
Print the factorial of the given integer.
PROGRAM
n=int(input("Enter a number: "))
# Initialize the factorial variable to 1
factorial = 1
Test case
Debug
Expected output Actual output
Enter·a·number:·4 Enter·a·number:·4
Factorial·of·4·is·24⏎ Factorial·of·4·is·24⏎
Output Format:
• A list of prime numbers up to n, each printed in a single line separated by
space.
PROGRAM
n=int(input(""))
primes = []
for num in range (2, n + 1):
is_prime=True
for i in range(2,num):
if num % i==0:
is_prime=False
break
if is_prime:
primes.append(str(num))
print(" ".join(primes))
Test case
d) You are tasked with creating a Python program to generate and print
the Fibonacci series up to 'n' terms.
19
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
EXPLANATION
Input Format:
The program expects an integer input 'n' from the user, which specifies the
number of terms in the Fibonacci series to generate.
Output Format:
After processing the input 'n', the program should output the Fibonacci series up
to 'n' terms, printed in a single line separated by spaces.
PROGRAM
Test case
20
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
The program should print the following outputs in order:
• The total number of characters in the input string.
• The repeated string (the original string repeated 10 times).
• The first character of the input string.
• The first three characters of the input string.
PROGRAM
str=input("")
print(len(str))
new_str=str*10
print(new_str)
print(str[0])
print(str[0:3])
21
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
b) Write a Python program to take a string as input and check given string
is Palindrome or not. A palindrome is a string that reads the same forwards
and backward.
EXPLANATION
Input Format:
A single line of input contains a string
Output Format:
If the input string is a palindrome, print "Palindrome", otherwise print "Not a
Palindrome"
PROGRAM
str=input()
rev =str[::-1]
if(str==rev):
22
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
print("Palindrome")
else:
print("Not a Palindrome")
Test case
Debug
Expected output Actual output
racecar racecar
Palindrome⏎ Palindrome⏎
Output Format:
• Print the concatenated string.
• Print the extracted substring based on the specified indices.
PROGRAM
23
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
str1=input("")
str2=input("")
str3=str1+str2
print(str3)
f=int(input(""))
l=int(input(""))
print(str3[f:l+1])
output
Test case
24
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
• The output will be a list containing the results of addition, subtraction,
multiplication, and division of the two numbers. If the second number is
zero, the division result will be "Cannot divide by zero".
PROGRAM
def Calc(a,b):
A=a+b
S=a-b
M=a*b
if(b==0):
div="Cannot divide by zero"
else:
div=a/b
return A,S,M,div
a=float(input("Number 1: "))
b=float(input("Number 2: "))
l=list(Calc(a,b))
print(l)
25
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Output Format: The output should print the following line with provided
inputs.
• Hello, {name}! You are {age} years old and you are from {country}
PROGRAM
def greet(x,y,z):
if x=='-1':
x="Dude"
26
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
if y==-1:
y=0
if z=='-1':
z="Space"
print(f'Hello, {x}! You are {y} years old and you are from {z}')
def get_user_input( ):
a=input('-1 for default: ')
b=int(input('-1 for default: '))
c=input('-1 for default: ')
greet(a,b,c)
get_user_input()
Test case 15 ms
Debug
Expected output Actual output
-1·for·default:·-1 -1·for·default:·-1
-1·for·default:·-1 -1·for·default:·-1
-1·for·default:·-1 -1·for·default:·-1
Hello,·Dude!·You·are·0·years·old·and· Hello,·Dude!·You·are·0·years·old·and·
you·are·from·Space⏎ you·are·from·Space⏎
27
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
• The total sum of the integers.
• The mean (average) of the integers, rounded to two decimal places.
• The maximum value among the integers.
PROGRAM
def calculate_stats(l):
numbers=[int(item) for item in l.split()]
a=sum(numbers)
m=a/len(numbers)
b=max(numbers)
return a,m,b
l=input()
a,m,b=calculate_stats(l)
print(f'{a}\n{round(m,2)}\n{b}')
Test case
28
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
EXPLANATION
Input Format:
The user is prompted to enter an integer n, for which the factorial needs to be
calculated
Output Format:
The program outputs the factorial of the input number n.
PROGRAM
def factorial_iterative(n):
f=1
if n < 0:
print("Factorial does not exist for negative numbers")
else:
for i in range(1,n + 1):
f=f*i
return f
29
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
n = int(input())
print(factorial_iterative(n))
Test case 12 ms
Debug
Expected output Actual output
10 10
3628800⏎ 3628800⏎
Input Format:
The user is prompted to enter an integer n, for which the factorial needs to be
calculated.
Output Format:
The program outputs the factorial of the input number n.
PROGRAM
def factorial_recursive(n):
30
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
else:
return factorial_recursive(n-1) * n
n = int(input())
print(factorial_recursive(n))
Test case
Input Format:
• Prompt the user to enter a number
Output Format:
• The output must be the double of the input number
PROGRAM
31
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Output Format:
• The program outputs the sum of the two numbers entered by the user.
PROGRAM
32
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
result=Add(x,y)
print(result)
Test case
c)Write a Python program that asks the user to input a list of numbers
separated by spaces. The program should then create a new list containing
only the even elements from the user's input list and print this new list
using lambda filter() expression.
EXPLANATION
Input Format:
• The input represents elements of the list separated with space (Integers).
Output Format:
33
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• The output represents a list of the even elements from the input list, prints
empty list [] if there are no even elements found.
PROGRAM
n=input()
nlist=list(map(int,n.split()))
Test case
34
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• 1 for addition
• 2 for subtraction
• 3 for multiplication
• 4 for division
Output Format:
Print the result of the operation. During "division by zero" print "Division by
zero" and "Invalid" for invalid operation.
PROGRAM
# Complete teh code to define the operations
operations = {
1: lambda x, y: x+y,
2: lambda x, y: x-y,
3: lambda x, y: x*y,
4: lambda x, y: x/y if y != 0 else "Division by zero"
}
Test case
35
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
EXPLANATION
Input Format:
• A single value which is an integer provided by the user to initialize the
random number generator.
Output Format:
• A string consisting of random printable ASCII characters with a length
between 7 and 10 characters.
PROGRAM
import random
36
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
seed_value = int(input())
random.seed(seed_value)
Test case
EXPLANATION
You need to create a Python program that performs the following operations on
a list:
Insert a value at a specified index:
37
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• Prompt the user for a value to insert and an index where the value should
be inserted.
• Print: Current List: [list contents]
my_list = []
def display_list():
print("Current List:", my_list)
while True:
print("1. Insert")
print("2. Remove")
print("3. Append")
print("4. Length")
print("5. Pop")
print("6. Clear")
print("7. Exit")
value=input("Value: ")
index=int(input("Index: "))
my_list.insert(index,value)
display_list()
elif choice=='2':
value=input("Value: ")
if value not in my_list:
print(f"{value} not found in list")
else:
my_list.remove(value)
display_list()
elif choice=='3':
value=input("Value: ")
my_list.append(value)
display_list()
elif choice=='4':
print(f"Length of the list: {len(my_list)}")
elif choice=='5':
if len(my_list)==0:
print("List is empty")
else:
print(f"Popped value: {my_list.pop()}")
display_list()
elif choice=='6':
my_list.clear()
print("List cleared")
display_list()
39
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
else:
break
Test case
41
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
42
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
43
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Functionality:
• Prompt the user for the size of the dictionary.
• Allow the user to input key-value pairs.
• Access a specific key and display its value.
• Update a value for a specific key.
44
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Input/Output Format:
• The first line should prompt for the dictionary size (an integer).
• For each key-value pair, prompt for the key and the value each in a new
line
• Once the keys are added print the dictionary
• Then Prompt the user to enter a key to access its value in the format "key
to access:<Key>" and display its value in the format "<Key>:<Value>" in
a new line.
• In the next line prompt the user to enter a key to update its value in the
format "key to update:<Key>" from the dictionary and prompt for the
new value in the next line as "new value:<Value>".
• After updating the value print "updated"
• In the next line display the length of the dictionary in the format "length
of the dictionary:<Length>"
• In the after line, prompt the user as "key to delete:<Key>" and once the
key is entered, delete the key and print the remaining dictionary. If the
key does not exist print "does not exist"
PROGRAM
#write your code here
s=int(input("size:"))
dictionary = {}
for i in range(s):
k=input("key:")
v=input("value:")
dictionary[k]=v
print(dictionary)
45
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
k1=input("key to access:")
if k1 in dictionary:
print(f"{k1}:{dictionary[k1]}")
k2=input("key to update:")
nv=input("new value:")
if k2 in dictionary:
dictionary[k2]=nv
print("updated")
else:
print("does not exist")
print(dictionary)
Test case
Functionality:
• Prompt the user to input a list of values separated by commas to create a
tuple.
• Display the length of the tuple.
• Allow the user to input an index to access and display a specific element.
• Allow the user to input start and end indices to perform slicing on the
tuple and display the sliced portion.
Input/Output Format:
Input: A single line of comma-separated values (e.g., value1,value2,value3).
Output: The length of the tuple in the format "Length: <Length>"
Input: Prompt for an index to access an element in the format "Index to access:
<Index>"
Output: The element at the specified index, if the index is out of range then
print "Index out of range"
Input: Prompt for start and end indices for slicing in the format:
Start index for slicing: <Start>
End index for slicing: <End>
Output: The sliced portion of the tuple, if the index is out of range then print
"Index out of range"
PROGRAM
48
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
if i < len(t):
print(t[i])
else:
print("Index out of range")
start=int(input("Start index for slicing: "))
end=int(input("End index for slicing: "))
if end<=len(t):
print(t[start:end])
else:
print("Index out of range")
5 ms
Maximum time
0.010 s
10.00 ms
2 out of 2 shown test case(s) passed
2 out of 2 hidden test case(s) passed
Test case 17 ms
Debug
Expected output Actual output
2,3,4,5,6,7 2,3,4,5,6,7
Length:·6⏎ Length:·6⏎
Index·to·access:·4 Index·to·access:·4
6⏎ 6⏎
Start·index·for·slicing:·1 Start·index·for·slicing:·1
End·index·for·slicing:·6 End·index·for·slicing:·6
49
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
• The output is the string obtained by converting all lowercase letters in the
input string to uppercase.
Note:
• The input string may consist of any characters, including lowercase and
uppercase letters, digits, and special characters.
• The code for creating objects, and invoking methods is already provided
in the editor. Your task is to implement the InOutString class based on
the given specifications.
PROGRAM
# write your code here...
class InOutString:
def __init__(self):
50
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
self.str=" "
def getString(self):
self.str=input()
def printString(self):
print(self.str.upper())
strObj = InOutString()
strObj.getString()
strObj.printString()
Test case
• Add Items: Users can add items to the cart, where each item has a
name and a price.
• Remove Items: Users can remove items from the cart by specifying
the item name. If the item does not exist, the program should indicate
that the removal was invalid.
51
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• Calculate Total Price: Users can calculate and return the total price
of all items currently in the cart.
EXPLANATION
Requirements:
• Implement the ShoppingCart class with methods to handle the above
functionalities.
• Use a menu-driven interface for user interaction.
• Ensure the program does not produce any unnecessary output when
running.
Input Format:
The program should display a menu with the following options:
Press 1 to add an item: User will be prompted to enter:
• item_name (string): Name of the item to add.
• item_price (float): Price of the item to add.
Press 2 to remove an item: User will be prompted to enter:
• item_name (string): Name of the item to remove. If the item is not found,
the program should print "Invalid".
Press 3 to calculate the total price: This option does not require any additional
input.
• Press 0 to exit the program.
This option ends the program.
Output Format:
When the user selects the option to calculate the total price, the output should be
displayed as:
• Total Price: <total_price> (formatted to two decimal places).
52
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
When an invalid item name is provided for removal, the output should be:
"Invalid"
class ShoppingCart:
# Write your code here...
def __init__(self):
self.items={}
def add_item(self):
item_name = input("Name: ").strip()
item_price = float(input("Price: "))
self.items[item_name] = item_price
def remove_item(self):
item_name = input("Remove: ").strip()
if item_name in self.items:
del self.items[item_name]
total_after_removal = sum(self.items.values())
print(f"Total after removal: {total_after_removal:.2f}")
else:
print("Invalid")
def calculate_total(self):
total_price = sum(self.items.values())
print(f"Total: {total_price:.2f}")
53
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
# User Interaction
if __name__ == "__main__":
cart = ShoppingCart()
while True:
print("1. Add")
print("2. Remove")
print("3. Total")
print("0. Exit")
choice = input().strip()
54
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
else:
print("Invalid")
Test case
55
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
56
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
57
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Input format:
• The two lines of the input are integers.
Output format:
• The first line is the integer after the addition operation.
• The second line is the integer after the multiplication operation.
58
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
PROGRAM
# write your code here..
class Calculation:
def __init__(self,x,y):
self.x=x
self.y=y
def addition(self,x,y):
return x+y
class My_Calculation(Calculation):
def multiplication(self):
return self.x * self.y
x=int(input())
y=int(input())
a=My_Calculation(x,y)
print(a.addition(x,y))
print(a.multiplication())
Test case
59
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Triangle Class:
1. perimeter(): Returns the sum of the three sides.
2. area(): Calculate the area using Heron's formula.
3. Formula: s⋅(s−side1)⋅(s−side2)⋅(s−side3) Where s=side1 +side2 +side32
.
Quadrilateral Class:
60
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Pentagon Class:
1. perimeter(): Returns five times the side length.
2. area(): Calculate the area of a regular pentagon.
3. Formula: 145(5+25) ∗ side2
Note:
• Display the area and perimeter of each shape up to 2 decimal places
• The main function has been provided to you in the editor, you need to fill
in the required code.
PROGRAM
from abc import ABC,abstractmethod
import math
# Base Class
class Polygon:
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
61
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
# Triangle Class
class Triangle(Polygon):
def __init__(self,s1,s2,s3):
self.s1=s1
self.s2=s2
self.s3=s3
def perimeter(self):
return self.s1+self.s2+self.s3
def area(self):
s= (self.s1+self.s2+self.s3)/2
return math.sqrt(s*(s-self.s1)*(s-self.s2)*(s-self.s3))
# Quadrilateral Class
class Quadrilateral(Polygon):
def __init__(self,l,b):
self.l = l
self.b=b
def perimeter(self):
return 2 * (self.l + self.b)
def area(self):
62
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
def perimeter(self):
return 5*self.s
def area(self):
a = (1/4) * math.sqrt(5 * (5+2 * math.sqrt(5))) * self.s **2
return a
# Main Program
def main():
print("1. Triangle")
print("2. Quadrilateral")
print("3. Pentagon")
if choice == 1:
side1 = float(input("side 1: "))
side2 = float(input("side 2: "))
side3 = float(input("side 3: "))
triangle = Triangle(side1, side2, side3)
print("Perimeter: {:.2f}".format(triangle.perimeter()))
63
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
print("Area: {:.2f}".format(triangle.area()))
elif choice == 2:
side1 = float(input("side 1: "))
side2 = float(input("side 2: "))
quadrilateral = Quadrilateral(side1, side2)
print("Perimeter: {:.2f}".format(quadrilateral.perimeter()))
print("Area: {:.2f}".format(quadrilateral.area()))
elif choice == 3:
side = float(input("side: "))
pentagon = Pentagon(side)
print("Perimeter: {:.2f}".format(pentagon.perimeter()))
print("Area: {:.2f}".format(pentagon.area()))
else:
print("Invalid choice")
if __name__ == "__main__":
main()
Test case
64
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Input Format:
• First line of input contains the names of the items available, separated by
a comma.
• Second line of input contains the prices of the items, separated by a
comma.
• Third line of input contains the name of the item which the user wants.
Output Format:
65
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• If the item is present: the first line contains the price of the item, the
second line contains the name of the item followed by "is available" and
the third line contains the message "Exception handled"
• If the item is not present, the first line contains the message "item not
available" followed by available item and their prices in each line and
the last line contains the message "Exception handled"
PROGRAM
def handle_exception(item, menu):
try:
print(menu[item])
print(f"{item} is available")
except:
print("item not available")
print("Available items:")
for menu_item, price in menu.items():
print(f"{menu_item}: {price}")
finally:
print("Exception handled")
menu_items = input()
item_prices = input()
user_input_item = input()
handle_exception(user_input_item, menu)
66
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Test case
Input Format:
• The program should prompt the user to enter the file name (string).
• The program should prompt the user to enter the text to write into the file.
Output Format:
67
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• The program should display the contents of the file after writing to it.
PROGRAM
#Type Content here...
fn = input()
text = input()
Test case
b) Write a Python program to merge the contents of two text files into a
third text file. The program should read the contents of the first two files,
concatenate them, and then write the combined content to the output file.
After merging, the program should display the content of the output file. If
any of the input files do not exist, the program should print an error
message.
EXPLANATION
68
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Input Format:
The program will take three lines of input:
• The name of the first input file (e.g., file1.txt).
• The name of the second input file (e.g., file2.txt).
• The name of the output file where the merged content will be written
(e.g., output.txt).
Output Format:
The output will display the merged content of the two input files.
If either input file does not exist, the program will print: "Not found"
PROGRAM
try:
with open(file1,"r") as f1:
text1=f1.read()
with open(file2,"r") as f2:
text2=f2.read()
except:
print("Not found")
else:
text3=text1+text2
with open(file3,"w") as f3:
69
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
f3.write(text3)
print(text3)
Test case
c) Write a function that reads a file and displays the following statistics:
• Number of words
• Number of vowels
• Number of blank spaces
• Number of lowercase letters
• Number of uppercase letters
EXPLANATION
Input Format:
Input: A single line containing the file path to the text file you want to analyze.
The path should be a valid string.
Output Format:
If the file is found and successfully read, output should be in the following
format:
70
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
71
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
• The NumPy array created from the user's input.
PROGRAM
import numpy as np
a = list(map(int,input().split()))
array = np.array(a)
print(array)
Test case
72
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
Output Format:
• The created NumPy array based on the input dimensions and elements.
• Dimensions (ndim): Number of dimensions of the array.
• Shape: Tuple representing the shape of the array (number of rows,
number of columns).
• Size: Total number of elements in the array.
PROGRAM
import numpy as np
rows, cols = map(int,input().split())
elements = []
for _ in range(rows):
elements.extend(map(int,input().split()))
print(array.ndim)
print(array.shape)
print(array.size)
Test case
c) You have been provided with exam scores for a group of students. Your
task is to analyze these scores using Python and pandas.
EXPLANATION
Instructions:
• Create a DataFrame: Using the data provided in the editor, create a
DataFrame that includes student names and their scores in different
subjects (Math, English, Science).
• Display the DataFrame: Print the DataFrame to show the student names
and their scores.
74
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
• Calculate Average Scores: Compute and display the average score for
each subject (Math, English, Science).
Output Format:
• Student Exam Scores: Display the DataFrame showing all students and
their scores followed by the print statement "Student Exam Scores:".
• Average Scores: Display the average score for each subject (Math,
English, Science) followed by the print statement "Average Score:".
PROGRAM
import pandas as pd
def analyze_student_scores():
data = {'Student': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Math': [85, 92, 78, 65, 89],
'English': [90, 88, 75, 82, 95],
'Science': [80, 85, 92, 70, 88]}
75
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY
analyze_student_scores()
Test case
76
PP LAB MANUAL(U24CS2L2)