0% found this document useful (0 votes)
79 views76 pages

PP LAB MANUAL 2nd Sem

The document is a lab manual for Python programming at Lords Institute of Engineering and Technology, detailing various exercises for input/output operations, conditional statements, and operator usage. It includes example programs for reading strings, numbers, temperature conversion, area calculation, and electricity bill computation, along with expected and actual outputs for test cases. Each section provides clear explanations and code snippets for students to follow and practice their Python skills.

Uploaded by

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

PP LAB MANUAL 2nd Sem

The document is a lab manual for Python programming at Lords Institute of Engineering and Technology, detailing various exercises for input/output operations, conditional statements, and operator usage. It includes example programs for reading strings, numbers, temperature conversion, area calculation, and electricity bill computation, along with expected and actual outputs for test cases. Each section provides clear explanations and code snippets for students to follow and practice their Python skills.

Uploaded by

160924733215
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

1.Introduction to Python Lab: Installation and Simple Output Display


a) Write a Python program to read a string and display it on the screen.
EXPLANATION
Input Format:
The input line reads a string.

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

• The first line reads an integer.


• The second line reads a float value.
• The third line reads a string.

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

2. Programs using Input Output Statements,Variables and Expressions


a) Write a Python program that prompts the user to enter a temperature in
Fahrenheit and converts it to a temperature in Celsius.
EXPLANATION
Note: Print the result up to 3 decimal places.

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

b) Write a Python program to print the area of a triangle.


EXPLANATION:
Sample Input & Output:
Base: 10
Height: 15
Area: 75

Note: Round off the result to two decimal places


PROGRAM

base = float(input("Base: "))


Height = float(input("Height: "))
Area=0.5 * base * Height
print("Area: " '%.2f'%Area)

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

3.Programs Using Various Operators


a) Write a python program for demonstrating the usage of comparison
operators.The program should read two integers from the input. Then,
perform each of the six comparison operations and print the result. Each
line of output should contain the comparison operation followed by a
boolean value (True or False), indicating whether the comparison holds
true or not.

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

Expected output Actual output


4 4
4 4
4·==·4·:·True⏎ 4·==·4·:·True⏎
4·!=·4·:·False⏎ 4·!=·4·:·False⏎
4·<·4··:·False⏎ 4·<·4··:·False⏎
4·<=·4·:·True⏎ 4·<=·4·:·True⏎

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

Sample Input and Output2:


str1: Regular Expression
str2: advanced
advanced in Regular Expression: False
PROGRAM
str1=input("str1: ")
str2=input("str2: ")
print(str2,"in",str1,":",str2 in str1)

7
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Test case

Expected output Actual output


str1:·Hello World Welcome to Python str1:·Hello World Welcome to Python
Programming Programming
str2:·Pro str2:·Pro
Pro·in·Hello·World·Welcome·to·Pytho Pro·in·Hello·World·Welcome·to·Pytho
n·Programming·:·True⏎ n·Programming·:·True⏎

c) Take two integers 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 input integers as shown in the example.

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: "))

#use identity operators and write the code


print("x is y",x is y)
print("x is not y",x is not y)
x = float(input("Enter a Float Number: "))

8
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

y = float(input("Enter the same Number: "))

#use identity operators and write the code


print("x is y",x is y)
print("x is not y",x is not y)

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

4. Programs using Conditional statements


a) Write a Python Program to determine whether the given number is
positive or negative using if-elif and else statements.
EXPLANATION

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

b) Take three integers a, b and c as inputs. Write a program to find the


largest of the given three inputs and print the result to the console as shown
in the examples.

EXPLANATION

Sample Input and Output:


a,b,c: 120,45,632
632

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])

if(a>b) and (a>c):


print(a)
elif(b>a)and(b>c):
print(b)
else:
print(c)

Test case

12
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


a,b,c:·120,45,632 a,b,c:·120,45,632
632⏎ 632⏎

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

Expected output Actual output


5 5
7 7

13
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


After·swapping:·a·=·7,·b·=·5⏎ After·swapping:·a·=·7,·b·=·5⏎
d) Write a program in Python to calculate and print the Electricity bill of a
given customer. The customer id, name and units consumed by the user
should be taken from the keyboard and display the total amount to pay to
the customer
The charge are as follows :
• For first 50 units Rs. 0.50/unit
• For next 100 units Rs. 0.75/unit
• For next 100 units Rs. 1.20/unit
• For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is to be added to the bill
EXPLANATION
Input Format:
The program expects the following inputs from the user:
• customer Id: Integer value representing the customer's ID
• customer name: String value representing the customer's name
• units consumed: Integer value representing the units of electricity
consumed
Output Format:
• After processing the input, the program will output the following details
in a formatted manner:
• Electricity bill details including Customer id, customer name, units,
amount, surcharge, and total amount
PROGRAM

customer_id = str(input("customer ID: "))


customer_name = str(input("customer name: "))
units = int(input("units consumed: "))
14
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

if units <= 50:


amount = units * 0.50
elif units <= 150:
amount = (50 * 0.5) +((units - 50)*0.75)
elif units <= 250:
amount = (50 * 0.5) +(100*0.75) +((units - 150)*1.20)
else:
amount = (50 * 0.5) +(100*0.75) +(100*1.20) +((units - 150)*1.50)
surcharge_amount = amount * 0.20
total_amount = amount + surcharge_amount

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

Expected output Actual output


customer·ID:·5184 customer·ID:·5184
customer·name:·Sanjeev customer·name:·Sanjeev
units·consumed:·52 units·consumed:·52
Electricity·Bill⏎ Electricity·Bill⏎
Customer·ID:·5184⏎ Customer·ID:·5184⏎
Customer·Name:·Sanjeev⏎ Customer·Name:·Sanjeev⏎
Units·Consumed:·52⏎ Units·Consumed:·52⏎
Amount:·Rs.·26.50⏎ Amount:·Rs.·26.50⏎
Surcharge·(20%):·Rs.·5.30⏎ Surcharge·(20%):·Rs.·5.30⏎
Total·Amount:·Rs.·31.80⏎ Total·Amount:·Rs.·31.80⏎

5 Programs using Iterative Statements


a)You are tasked with writing a program that reverses a given integer. The
program should take an integer input from the user and output the
reversed number.
EXPLANATION
Input Format:
The first line contains an integer n.

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

while (number > 0):


# Logic
remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10
print("Reverse of a number :",revs_number)

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⏎

b) You are tasked with writing a program to calculate the factorial of a


given non-negative integer. The program should take an integer input from
the user and output the factorial of that number.
EXPLANATION

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

# Calculate the factorial using a for loop


for i in range(1, n + 1):
factorial *= i

# Output: The factorial of the number


print(f"Factorial of {n} is {factorial}")

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⏎

c) Write a Python program to find and print all prime numbers up to a


given number.
EXPLANATION
Input Format:
• A single integer n representing the upper limit for finding prime numbers.
18
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

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

Expected output Actual output


10 10
2·3·5·7⏎ 2·3·5·7⏎

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

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


a, b = 0, 1
count = 0
c=b
while count<n:
print(a, end=" ")
a,b=b,a+b
count=count+1

Test case

Expected output Actual output


Enter·the·number·of·terms:·3 Enter·the·number·of·terms:·3
0·1·1· 0·1·1·

20
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

6. Programs using Strings


a) Write a Python program that performs several operations on a given
string input from the user. Your program should accomplish the following
tasks:
1. Count and display the total number of characters in the input string.
2. Create and display a new string that consists of the original string
repeated 10 times.
3. Extract and display the first character of the input string.
4. Extract and display the first three characters of the input string.
EXPLANATION
Input Format:
A single line of input containing a string.

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

Expected output Actual output


chandlerbing chandlerbing
12⏎ 12⏎
chandlerbingchandlerbingchandlerbing chandlerbingchandlerbingchandlerbing
chandlerbingchandlerbingchandlerbing chandlerbingchandlerbingchandlerbing
chandlerbingchandlerbingchandlerbing chandlerbingchandlerbingchandlerbing
chandlerbing⏎ chandlerbing⏎
c⏎ c⏎
cha⏎ cha⏎

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⏎

c) Write a program to create, concatenate, and print a string and access a


substring from a given string.
EXPLANATION
Input Format:
• The first line contains the first string (string1).
• The second line contains the second string (string2).
• Once the concatenated string is printed, then the next line prompts the
user to enter an integer representing the starting index for the substring.
• The last line prompts the user to enter an integer representing the ending
index for the substring.

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

Expected output Actual output


Yanky Yanky
Franky Franky
YankyFranky⏎ YankyFranky⏎
1 1
3 3
ank⏎ ank⏎

7. Programs using User defined functions


values to calculate sum, mean and maximum of the given list of numbers.
a) Write a Python program to create a function calc() that takes two
numbers as input and returns a list containing the results of addition,
subtraction, multiplication, and division of the two numbers.
EXPLANATION
Input Format:

24
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

• The input will be two floating-point numbers each on a new line


respectively.

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

#write your code here

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

Expected output Actual output


Number·1:·123.456 Number·1:·123.456
Number·2:·12.4 Number·2:·12.4
[135.856,·111.056,·1530.85440000000 [135.856,·111.056,·1530.85440000000
02,·9.956129032258065]⏎ 02,·9.956129032258065]⏎

b) Write a program to define a function using default arguments.


EXPLANATION
Input Format:
• First line of Input should prompt the user to enter the name by displaying
"-1 for default: ", If -1 is entered, the default value "Dude" is used.
• Second line of input should prompt the user to enter the age by
displaying: "-1 for default: ", If -1 is entered, the default value "0" is used.
• Third line of input should prompt the user to enter the country by
displaying: "-1 for default: ", If -1 is entered, the default value "Space" is
used.

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⏎

c) Write a Python program that defines a function with multiple return


values to calculate sum, mean and maximum of the given list of numbers.
EXPLANATION
Input Format:
• A list of space-separated integers.

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

Expected output Actual output


12 23 34 45 56 67 78 89 12 23 34 45 56 67 78 89
404⏎ 404⏎
50.5⏎ 50.5⏎
89⏎ 89⏎

28
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

d) Write a Python function to calculate the factorial of a number

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⏎

e)Write a Python function to calculate the factorial of a number using


recursion.
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_recursive(n):

# write the code..


if n ==1:
return 1

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

Expected output Actual output


10 10
3628800⏎ 3628800⏎

8. Programs using Lamda function


a)Write a Python program that defines a lambda function to double the
given number. The program should take a number as input from the user,
use the lambda function to compute the calculation and print the result.
EXPLANATION

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

multiply = lambda x:x+x

# Define a lambda function to double the number

# Read the input from user


x = int(input())
# Compute the result using the lambda function
result = multiply(x)
print(result)

Test case

Expected output Actual output


2 2
4⏎ 4⏎

b) Write a Python program that defines a lambda function to add two


numbers. The program should take two numbers as input from the user,
use the lambda function to compute their addition and print the result.
EXPLANATION
Input Format:
• The program expects two integer inputs from the user, one after the other.

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

Add = lambda x, y:x+y# Define a lambda function to add two numbers


# Read two numbers from the user
x=int(input())
y=int(input())

# Compute the addition using the lambda function

result=Add(x,y)
print(result)

Test case

Expected output Actual output


3 3
4 4
7⏎ 7⏎

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()))

even_elements = list(filter(lambda x:x%2==0,nlist))

# Print the new list of even elements


print(even_elements)

Test case

Expected output Actual output


13579 13579
[]⏎ []⏎

d Write a Python program that implements a simple calculator using


lambda functions. The calculator should be able to perform basic
arithmetic operations: addition, subtraction, multiplication, and division.
The user should be able to input two numbers and select an operation by
entering a corresponding number (1 for addition, 2 for subtraction, 3 for
multiplication, 4 for division).
EXPLANATION
Input Format:
The first line contains two space-separated integers: num1 and num2.
The second line contains an integer representing the operation:

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"
}

num1, num2 = map(int, input().split())


i = int(input())
if i in operations:
result = operations[i](num1, num2)
print(result)

Test case

35
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


10 5 10 5
1 1
15⏎ 15⏎

e) Write a Python programs using Lambda function that takes an


integer seed_value as input. This program should generate a random
password with a length between 7 and 10 characters. Each character of the
password should be randomly selected from ASCII positions 33 to 126
using the provided seed_value to initialize the random number generator.
The program should return the generated password.

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

generate_random_password = lambda seed_value:


''.join(chr(random.randint(33,126)) for _ in range(random.randint(7, 10)))

# write your code here..

36
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

seed_value = int(input())
random.seed(seed_value)

# Generate and print the password


random_password = generate_random_password(seed_value)
print("Randomly generated password: {}".format(random_password))

Test case

Expected output Actual output


5 5
Randomly·generated·password:·Nytd$\ Randomly·generated·password:·Nytd$\
@t'⏎ @t'⏎

9. Programs using Data Structure


a) Implement a list manipulation program in Python that allows users to
perform various operations on a list. Your program should handle all user
inputs, display the current state of the list, and provide appropriate
feedback for each operation.

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]

Remove a value from the list:


• Prompt the user for a value to remove.
• If the value is found and removed, print: Current List: [list contents]
• If the value is not found, print: [value] not found in list.
PROGRAM

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")

choice = input("Choice: ")

# Write your code here...


if choice=='1':
38
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

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

Expected output Actual output


1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·1 Choice:·1
Value:·10 Value:·10
Index:·0 Index:·0
Current·List:·['10']⏎ Current·List:·['10']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·1 Choice:·1
40
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


Value:·20 Value:·20
Index:·1 Index:·1
Current·List:·['10',·'20']⏎ Current·List:·['10',·'20']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·1 Choice:·1
Value:·30 Value:·30
Index:·2 Index:·2
Current·List:·['10',·'20',·'30']⏎ Current·List:·['10',·'20',·'30']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·1 Choice:·1
Value:·40 Value:·40
Index:·3 Index:·3

41
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


Current·List:·['10',·'20',·'30',·'40']⏎ Current·List:·['10',·'20',·'30',·'40']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·2 Choice:·2
Value:·30 Value:·30
Current·List:·['10',·'20',·'40']⏎ Current·List:·['10',·'20',·'40']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·3 Choice:·3
Value:·50 Value:·50
Current·List:·['10',·'20',·'40',·'50']⏎ Current·List:·['10',·'20',·'40',·'50']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎

42
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·4 Choice:·4
Length·of·the·list:·4⏎ Length·of·the·list:·4⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·5 Choice:·5
Popped·value:·50⏎ Popped·value:·50⏎
Current·List:·['10',·'20',·'40']⏎ Current·List:·['10',·'20',·'40']⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·6 Choice:·6

43
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


List·cleared⏎ List·cleared⏎
Current·List:·[]⏎ Current·List:·[]⏎
1.·Insert⏎ 1.·Insert⏎
2.·Remove⏎ 2.·Remove⏎
3.·Append⏎ 3.·Append⏎
4.·Length⏎ 4.·Length⏎
5.·Pop⏎ 5.·Pop⏎
6.·Clear⏎ 6.·Clear⏎
7.·Exit⏎ 7.·Exit⏎
Choice:·7 Choice:·7

b) Create a program that allows the user to perform the following


operations on a dictionary:
• Add key-value pairs to the dictionary.
• Access a value by key.
• Update a value by key.
• Get the length of the dictionary.
• Delete a key-value pair from the dictionary.
EXPLANATION

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

• Display the length of the dictionary.


• Delete a key-value pair by key.

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("Length of the dictionary:",len(dictionary))


k3=input("key to delete:")
if k3 in dictionary:
del dictionary[k3]
else:
print("does not exist")

print(dictionary)

Test case

Expected output Actual output


size:4 size:4
key:main key:main
46
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


value:ross value:ross
key:main2 key:main2
value:ichigo value:ichigo
key:main3 key:main3
value:chandler value:chandler
key:main45 key:main45
value:gunther value:gunther
{'main':·'ross',·'main2':·'ichigo',·'main3' {'main':·'ross',·'main2':·'ichigo',·'main3'
:·'chandler',·'main45':·'gunther'}⏎ :·'chandler',·'main45':·'gunther'}⏎
key·to·access:main45 key·to·access:main45
main45:gunther⏎ main45:gunther⏎
key·to·update:man2 key·to·update:man2
new·value:joey new·value:joey
does·not·exist⏎ does·not·exist⏎
Length·of·the·dictionary:·4⏎ Length·of·the·dictionary:·4⏎
key·to·delete:main key·to·delete:main
{'main2':·'ichigo',·'main3':·'chandler',·' {'main2':·'ichigo',·'main3':·'chandler',·'
main45':·'gunther'}⏎ main45':·'gunther'}⏎

c) Create a program that allows the user to perform the following


operations on a tuple:
• Find the length of the tuple.
• Access an element by index.
• Perform slicing operations on the tuple.
EXPLANATION
47
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

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

# write the code..


v=input()
t=tuple(v.split(","))
print("Length:",len(t))

i=int(input("Index to access: "))

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

Expected output Actual output


('3',·'4',·'5',·'6',·'7')⏎ ('3',·'4',·'5',·'6',·'7')⏎

10. Programs using OOPS Concept


a) Create a Python class InOutString according to the given specifications:
1. Initialize an instance variable to an empty string in the constructor.
2. Implement a method getString that takes user input and assigns it to
the instance variable.
3. Implement another method printString to print the string stored in
the instance variable after converting all lowercase letters to
uppercase.
EXPLANATION
Input Format:
• The input is a string containing various characters.

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

Expected output Actual output


pythON@123 pythON@123
PYTHON@123⏎ PYTHON@123⏎

b) Create a Python program that defines a class representing a shopping


cart. The class should include the following functionalities:

• 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()

# Write your code here...


# Write your code here...
if choice == "1":
cart.add_item()
elif choice == "2":
cart.remove_item()
elif choice == "3":
cart.calculate_total()
elif choice == "0":
print("Exiting")
break

54
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

else:
print("Invalid")

Test case

Expected output Actual output


1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
1 1
Name:·Apple Name:·Apple
Price:·0.25 Price:·0.25
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
3 3
Total:·0.25⏎ Total:·0.25⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
2 2
Remove:·Apple Remove:·Apple

55
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


Total·after·removal:·0.00⏎ Total·after·removal:·0.00⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
3 3
Total:·0.00⏎ Total:·0.00⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
1 1
Name:·Apple Name:·Apple
Price:·0.35 Price:·0.35
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
1 1
Name:·Banana Name:·Banana
Price:·0.25 Price:·0.25
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎

56
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


0.·Exit⏎ 0.·Exit⏎
3 3
Total:·0.60⏎ Total:·0.60⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
2 2
Remove:·Guava Remove:·Guava
Invalid⏎ Invalid⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
2 2
Remove:·Banana Remove:·Banana
Total·after·removal:·0.35⏎ Total·after·removal:·0.35⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
3 3
Total:·0.35⏎ Total:·0.35⏎
1.·Add⏎ 1.·Add⏎

57
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
5 5
Invalid⏎ Invalid⏎
1.·Add⏎ 1.·Add⏎
2.·Remove⏎ 2.·Remove⏎
3.·Total⏎ 3.·Total⏎
0.·Exit⏎ 0.·Exit⏎
0 0
Exiting⏎ Exiting⏎

c) Define a base class Calculation with a constructor that takes two


parameters. Implement a method addition in the Calculation class.
The addition method should take the two parameters and return their sum.
EXPLANATION
Create a child class My_Calculation that inherits from the Calculation class.
In the child class, implement a method multiplication that returns the product
of the two parameters that are inherited from the base class.

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

Expected output Actual output


1 1
2 2
3⏎ 3⏎
2⏎ 2⏎

d) Develop a Python program to calculate the area and perimeter of


different polygons using an inheritance hierarchy. You will create a base
class Polygon with abstract methods for calculating area and perimeter.
Then, implement subclasses for specific polygon types Triangle,
Quadrilateral, and Pentagon that extend this base class. Your program
should prompt users to input the geometric dimensions of their chosen
polygon and then display the calculated area and perimeter.
EXPLANATION

Abstract Base Class:


Define an abstract class Polygon with two abstract methods:
1. area(): Method to calculate the area of the polygon.
2. perimeter(): Method to calculate the perimeter of the polygon.

Implement Subclasses with the described methods:

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

1. perimeter(): Assume the quadrilateral is a rectangle, Return the perimeter.


2. Formula: 2(side1 + side2).
3. area(): Assuming the quadrilateral is a rectangle, calculate the area.
4. Formula: side1 ∗ side2.

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

return self.l * self.b


# Pentagon Class
class Pentagon(Polygon):
def __init__(self,s):
self.s = s

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")

choice = int(input("choice: "))

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

Expected output Actual output


1.·Triangle⏎ 1.·Triangle⏎
2.·Quadrilateral⏎ 2.·Quadrilateral⏎
3.·Pentagon⏎ 3.·Pentagon⏎
choice:·1 choice:·1
side·1:·12.2 side·1:·12.2

64
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


side·2:·13.4 side·2:·13.4
side·3:·14.5 side·3:·14.5
Perimeter:·40.10⏎ Perimeter:·40.10⏎
Area:·76.22⏎ Area:·76.22⏎
e) Create a Python program to manage a menu of items with their
corresponding prices for a restaurant. Follow the given instructions:
• Create a dictionary where keys are items (strings) and values are
their prices (floats).
• Take an item name from the user.
• Print its corresponding price.
• Print the item name followed by "is available".
• Handle the exception if the user-given item is not found with the
message "item not available".
• Use the "finally" keyword to print the message "Exception handled".
EXPLANATION
Constraints:
• Prices must be positive floats.

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()

menu = dict(zip(menu_items.split(','), map(float, item_prices.split(','))))

user_input_item = input()
handle_exception(user_input_item, menu)

66
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Test case

Expected output Actual output


burger,pizza,pasta,salad,soup burger,pizza,pasta,salad,soup
5.99,8.99,7.49,4.99,3.99 5.99,8.99,7.49,4.99,3.99
pasta pasta
7.49⏎ 7.49⏎
pasta·is·available⏎ pasta·is·available⏎
Exception·handled⏎ Exception·handled⏎

11. Programs using Files

a) Create a Python program that writes user-provided contents to a


specified file and then displays the contents of that file.
EXPLANATION
Requirements:
• The program should prompt the user to enter the file name (string) where
the contents will be written.
• The user should be prompted to enter the text that will be written to the
file.
• After writing the text, the program should read the contents of the file and
display them.

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()

with open(fn,"w") as f1:


f1.write(text)

with open(fn,"r") as f2:


print(f2.read())

Test case

Expected output Actual output


input.txt input.txt
Python is a high level language Python is a high level language
Python·is·a·high·level·language⏎ Python·is·a·high·level·language⏎

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

#Type Content here...


file1 = input()
file2 = input()
file3 = input()

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

Expected output Actual output


input.txt input.txt
input1.txt input1.txt
output.txt output.txt
hi!·welcome·to·programming.Program hi!·welcome·to·programming.Program
ming·is·easy⏎ ming·is·easy⏎

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

Word Count: <number_of_words>


Vowel Count: <number_of_vowels>
Space Count: <number_of_spaces>
Lowercase Count: <number_of_lowercase_letters>
Uppercase Count: <number_of_uppercase_letters>
If the file is not found, output should be: "File not found."
PROGRAM
def filepath(fp):
try:
with open(fp, "r") as file:
content = file.read()
num_words = len(content.split())
num_vowels = sum(1 for char in content if char.lower() in
'aieou')
num_spaces = content.count(' ')
num_lowercase = sum(1 for char in content if char.islower())
num_uppercase = sum(1 for char in content if char.isupper())
print(f"Word Count: {num_words}")
print(f"Vowel Count: {num_vowels}")
print(f"Space Count: {num_spaces}")
print(f"Lowercase Count: {num_lowercase}")
print(f"Uppercase Count: {num_uppercase}")
except:
print("File not found.")
file=input()
filepath(file)
Test case

71
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

Expected output Actual output


file1.txt file1.txt
Word·Count:·15⏎ Word·Count:·15⏎
Vowel·Count:·21⏎ Vowel·Count:·21⏎
Space·Count:·12⏎ Space·Count:·12⏎
Lowercase·Count:·50⏎ Lowercase·Count:·50⏎
Uppercase·Count:·3⏎ Uppercase·Count:·3⏎

12. Python programs to practice some basic library modules


a) Write a Python program that prompts the user to enter numeric
elements for a NumPy array. The program should create the NumPy array
using the entered elements and display it.
EXPLANATION
Input Format:
• A single line of space-separated numeric values entered by the user.

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

Expected output Actual output


12345 12345
[1·2·3·4·5]⏎ [1·2·3·4·5]⏎

b) Write a python program to demonstrate the usage of ndim, shape and


size for a Numpy Array. The program should create a NumPy array using
the entered elements and display it. Assume all input elements are valid
numeric values.
EXPLANATION
Input Format:
• User inputs the number of rows and columns with space separated values.
• User inputs elements of the array row-wise followed line by line,
separated by spaces.

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()))

array = np.array(elements).reshape(rows, cols)


print(array)
73
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

print(array.ndim)
print(array.shape)
print(array.size)

Test case

Expected output Actual output


34 34
1234 1234
5678 5678
9 10 11 12 9 10 11 12
[[·1··2··3··4]⏎ [[·1··2··3··4]⏎
·[·5··6··7··8]⏎ ·[·5··6··7··8]⏎
·[·9·10·11·12]]⏎ ·[·9·10·11·12]]⏎
2⏎ 2⏎
(3,·4)⏎ (3,·4)⏎
12⏎ 12⏎

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]}

print("Student Exam Scores:")


df=pd.DataFrame(data)
print(df)
average_score = df[['Math', 'English', 'Science']].mean()
print("Average Score:")
print(average_score)

# write your code here..

75
PP LAB MANUAL(U24CS2L2)
LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

analyze_student_scores()

Test case

Expected output Actual output


Student·Exam·Scores:⏎ Student·Exam·Scores:⏎
···Student··Math··English··Science⏎ ···Student··Math··English··Science⏎
0····Alice····85·······90·······80⏎ 0····Alice····85·······90·······80⏎
1······Bob····92·······88·······85⏎ 1······Bob····92·······88·······85⏎
2··Charlie····78·······75·······92⏎ 2··Charlie····78·······75·······92⏎
3····David····65·······82·······70⏎ 3····David····65·······82·······70⏎
4······Eva····89·······95·······88⏎ 4······Eva····89·······95·······88⏎
Average·Score:⏎ Average·Score:⏎
Math·······81.8⏎ Math·······81.8⏎
English····86.0⏎ English····86.0⏎
Science····83.0⏎ Science····83.0⏎
dtype:·float64⏎ dtype:·float64⏎

76
PP LAB MANUAL(U24CS2L2)

You might also like