Python Lab Record
Python Lab Record
Aim:
In a classroom, there are three students of varying ages. The teacher, who is responsible for the class, has a
Page No: 1
specific task at hand to determine the oldest student among the three. To achieve this, the teacher plans to
develop a Python program that takes the ages of the students as input and identifies the eldest among them.
Could you help the teacher in crafting this Python program?
ID: 249X5A04L9
Input format:
The first three lines are the integers that represent the ages of the three students.
Output format:
The output is the integer that represents the age of the elder student.
Source Code:
eldestAge.py
2023-2027-ECE-B
if a>b:
if a>c:
print(a)
else:
if b>c: print(b)
else:print(c)
User Output
12
14
13
14
Test Case - 2
User Output
11
43
23
43
Exp. Name: Prime numbers from 2 to the given
S.No: 2 Date: 2024-10-25
positive number
Aim:
Page No: 2
Implement a program that takes an integer n input from the user and prints all the prime numbers from 2 to n.
Input format:
ID: 249X5A04L9
• The input contains a positive integer n.
Output Format:
• Contains the list of prime numbers up to n
Example:
Input:
10
Output:
[2, 3, 5, 7]
Constraints:
• The input n should be a positive integer greater than or equal to 2.
2023-2027-ECE-B
• The algorithm should be efficient, aiming for a time complexity of approximately O(n ∗ sqrt(n)) where n
is the input number.
• The algorithm should handle large inputs reasonably well, without consuming excessive memory or taking
an unreasonable amount of time to execute.
Source Code:
CTP32252.py
User Output
10
[2, 3, 5, 7]
Test Case - 2
User Output
20
[2, 3, 5, 7, 11, 13, 17, 19]
Test Case - 3
User Output
Page No: 3
30
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
ID: 249X5A04L9
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 3 Exp. Name: Swap two numbers Date: 2024-10-16
Aim:
Write a Python program that reads two numbers from the user and swaps their values using only two variables.
Page No: 4
Source Code:
swapping.py
ID: 249X5A04L9
b=float(input("Enter the second number: "))
print("Original numbers:\nFirst number:",a)
print("Second number:",b)
print("Swapped numbers:\nFirst number:",b)
print("Second number:",a)
2023-2027-ECE-B
User Output
Enter the first number:
2
Enter the second number:
3
Original numbers:
Test Case - 2
User Output
Enter the first number:
-3.5
Enter the second number:
2.5
Original numbers:
First number: -3.5
Second number: 2.5
Swapped numbers:
First number: 2.5
Second number: -3.5
Exp. Name: Arithmetic Operations (Addition,
S.No: 4 Date: 2024-10-19
Subtraction, Multiplication, Division)
Aim:
Page No: 5
Write a program to read two integer inputs from the user and perform the following arithmetic operations
addition, subtraction, multiplication, and division, and print the result.
Input layout:
The first two lines represent the input of 2 integers num1 and num2.
ID: 249X5A04L9
Output layout:
First line should print the addition of provided inputs.
Second line should print the subtraction of provided inputs.
Third line should print the multiplication of provided inputs.
Fourth line should print the division of provided inputs.
Example1:
Input:
num1: 40
num2: 20
2023-2027-ECE-B
Output:
Addition of 40 and 20 = 60
Subtraction of 40 and 20 = 20
Multiplication of 40 and 20 = 800
Division of 40 and 20 = 2.0
Source Code:
num1=int(input("num1: "))
num2=int(input("num2: "))
a=num1 + num2
print("Addition of",num1,"and",num2,"=",a)
b=num1 - num2
print("Subtraction of",num1, "and",num2,"=",b)
c=num1 * num2
print("Multiplication of",num1,"and",num2,"=",c)
d=num1/num2
print("Division of",num1,"and",num2,"=",d)
User Output
num1:
40
num2:
20
Addition of 40 and 20 = 60
Subtraction of 40 and 20 = 20
Multiplication of 40 and 20 = 800
Division of 40 and 20 = 2.0
Test Case - 2
Page No: 6
User Output
num1:
4
ID: 249X5A04L9
num2:
6
Addition of 4 and 6 = 10
Subtraction of 4 and 6 = -2
Multiplication of 4 and 6 = 24
Division of 4 and 6 = 0.6666666666666666
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 5 Exp. Name: logical operator Date: 2024-10-21
Aim:
Write a Python program that demonstrates the usage of logical operators. Your program should read two integer
Page No: 7
values from the user and perform logical operations (and, or, not). Display the corresponding output for each
operation.
Input Format:
• The program should read two integer values from the user, each on a new line.
ID: 249X5A04L9
Output Format:
• Print the result of num1 and num2 in the format "{num1} and {num2}: result"
• Print the result of num1 or num2 in the format "{num1} or {num2}: result"
• Print the result of not num1 in the format "not {num1}: result"
• Print the result of not num2 in the format "not {num2}: result"
Source Code:
logicoperator.py
2023-2027-ECE-B
y=int(input())
print(x," and ",y,": ",x and y,sep='')
print(x," or ",y,": ",x or y,sep='')
print("not ",x,": ",not x,sep='')
print("not ",y,": ",not y,sep='')
User Output
3
4
3 and 4: 4
3 or 4: 3
not 3: False
not 4: False
Test Case - 2
User Output
0
1
0 and 1: 0
0 or 1: 1
not 0: True
not 1: False
0
0
0 or 0: 0
0 and 0: 0
not 0: True
not 0: True
User Output
Test Case - 3
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 8
S.No: 6 Exp. Name: Comparison Operators Date: 2024-10-19
Aim:
Write a python program for demonstrating the usage of comparison operators.The program should read two
Page No: 9
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.
Input format:
ID: 249X5A04L9
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
Source Code:
operators.py
#write your code here
num1=int(input())
2023-2027-ECE-B
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}")
User Output
4
4
4 == 4 : True
4 != 4 : False
4 < 4 : False
4 <= 4 : True
4 > 4 : False
4 >= 4 : True
Test Case - 2
User Output
3
2
3 == 2 : False
3 != 2 : True
3 < 2 : False
3 <= 2 : False
3 > 2 : True
3 >= 2 : True
Page No: 10
Test Case - 3
User Output
5
ID: 249X5A04L9
5
5 == 5 : True
5 != 5 : False
5 < 5 : False
5 <= 5 : True
5 > 5 : False
5 >= 5 : True
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
Exp. Name: Writing an example using identity
S.No: 7 Date: 2024-10-21
operator "is not"
Aim:
Page No: 11
Take two integers x and y as input from the console using input() function. Using the identity operator
is not check if x and y are same objects or not, print to the console, the result of the two input integers as
shown in the example.
ID: 249X5A04L9
Sample Input and Output 1:
x: -8
y: -8
-8 is not -8 True
x: 256
y: 256
256 is not 256 False
2023-2027-ECE-B
Source Code:
IdenopExample3.py
User Output
x:
-8
y:
-8
-8 is not -8 True
Test Case - 2
User Output
x:
256
y:
256
256 is not 256 False
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 12
S.No: 8 Exp. Name: Bitwise Operator Date: 2024-10-21
Aim:
Take two integers x and y as inputs from the console using input() function. For each bitwise operator ( >> , <<,
Page No: 13
&, |, ~, and ^ ), print to the console, the result of applying these operators on the two input integers as shown in
the example.
ID: 249X5A04L9
y: 20
52 >> 20 is 0
52 << 20 is 54525952
52 & 20 is 20
52 | 20 is 52
~ 52 is -53
52 ^ 20 is 32
Source Code:
Bitopexample1.py
x=int(input('x: '))
y=int(input('y: '))
2023-2027-ECE-B
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)
User Output
x:
30
y:
2
30 >> 2 is 7
30 << 2 is 120
30 & 2 is 2
30 | 2 is 30
~ 30 is -31
30 ^ 2 is 28
Test Case - 2
User Output
x:
10
y:
20
~ 10 is -11
10 & 20 is 0
10 ^ 20 is 30
10 | 20 is 30
10 >> 20 is 0
10 << 20 is 10485760
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 14
Exp. Name: Write a program on assignment
S.No: 9 Date: 2024-10-19
operators =,+=,-= and *=
Aim:
Page No: 15
Take two integers x and y as inputs from the console using input() function. For each assignment operator (
= , += , -= , and *= ), print to the console, the result of applying these operators on the two input integers as
shown in the example.
ID: 249X5A04L9
Assumption:
• y is a non-zero integer
Sample Input and Output:
x: 20
y: 30
x = y: 30
x += y: 50
x -= y: -10
x *= y: 600
Hint: Before every assignment operation, reset the values of x and y to the initial values.
2023-2027-ECE-B
Source Code:
Assignexample2.py
print("x += y:",x+y)
print("x -= y:",x-y)
print("x *= y:",x*y)
User Output
x:
20
y:
30
x = y: 30
x += y: 50
x -= y: -10
x *= y: 600
Test Case - 2
3
6
y:
x:
x = y: 3
x -= y: 3
x += y: 9
x *= y: 18
User Output
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 16
S.No: 10 Exp. Name: Ternary Operator Date: 2024-10-21
Aim:
Write a python program to find the maximum value of given two numbers using ternary operator.
Page No: 17
Input Format:
• First line should prompt the user to enter first integer
• Second line should prompt the user to enter second integer
ID: 249X5A04L9
Output Format:
• Output should print the maximum value using ternary operator
Source Code:
ternary.py
x=int(input())
y=int(input())
max=x if x>y else y
print(max)
2023-2027-ECE-B
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
91
Test Case - 2
User Output
15
-23
15
S.No: 11 Exp. Name: Membership Operator Date: 2024-10-21
Aim:
Write a python program to demonstrate membership operator.
Page No: 18
Predefined list of integers is already provided to you.
Input:
• The program should prompt the user to enter an integer number.
ID: 249X5A04L9
Output:
• Use "in" operator to check whether the given integer is present in the list or not and print the result.
• Use "not in" operator to check whether the given integer is not present in the list and print the result.
Source Code:
membership.py
x=int(input())
print(x in num_list)
2023-2027-ECE-B
print(x not in num_list)
Test Case - 2
User Output
-3
False
True
Test Case - 3
User Output
5
True
False
Test Case - 4
54
True
False
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 19
Exp. Name: Write a program to addition,
S.No: 12 subtraction and multiplication and division of two Date: 2024-10-19
complex numbers.
Page No: 20
Aim:
Take two complex numbers as input from the console. For each arithmetic operator( + , - , * , and / ),
perform these operations on the two complex numbers and print the result as shown in the example.
ID: 249X5A04L9
Sample Input and Output:
c1: 10+3j
c2: 14+3j
a1 + b2 = (24+6j)
a1 - b2 = (-4+0j)
a1 * b2 = (131+72j)
a1 / b2 = (0.7268292682926829+0.05853658536585366j)
Source Code:
ComplexNums.py
2023-2027-ECE-B
c1=complex(input("c1: "))
c2=complex(input("c2: "))
print("a1 + b2 =", c1+c2)
print("a1 - b2 =",c1-c2)
print("a1 * b2 =",c1*c2)
print("a1 / b2 =",c1/c2)
User Output
c1:
10+3j
c2:
41+3j
a1 + b2 = (51+6j)
a1 - b2 = (-31+0j)
a1 * b2 = (401+153j)
a1 / b2 = (0.24792899408284022+0.055029585798816574j)
Test Case - 2
User Output
c1:
5+10j
c2:
25+15j
a1 - b2 = (-20-5j)
a1 * b2 = (-25+325j)
a1 / b2 = (0.3235294117647059+0.20588235294117646j)
Page No: 21
ID: 249X5A04L9
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 13 Exp. Name: Print Multiplication Table Date: 2024-10-25
Aim:
Write a python program to print multiplication table of given number in given format.
Page No: 22
Input:
• Prompt the user to enter a number (n) for which they want to generate the multiplication table.
Output Format:
ID: 249X5A04L9
• Print the multiplication table of the entered number in the following format for numbers from 1 to 10:
• Each line should display the multiplication operation in the format {n}*{i}={result}, where {n} is the entered
number, {i} ranges from 1 to 10, and {result} is the product of {n} and {i}.
Source Code:
multiplication_table.py
2023-2027-ECE-B
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Test Case - 2
User Output
Enter a number :
13
13*1=13
13*2=26
13*3=39
13*4=52
13*5=65
13*6=78
13*7=91
13*9=117
13*8=104
13*10=130
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 23
S.No: 14 Exp. Name: Series Calculation 1 Date: 2024-10-25
Aim:
Your friend is a mathematician, and he needs your help in verifying a mathematical series. You have three inputs a
Page No: 24
, b, and N . Your task is to print the output with the series that results from the following equation
1 2 N
a + b , a + b , .., a + b
Input Format:
• The first line of the input consists of an integer, a.
ID: 249X5A04L9
• The second line of the input consists of an integer b representing the base for the series.
• The third line of the input consists an integer, N representing the number of terms in the series.
Output Format:
• The output is a single line containing the space-separated terms of the given series.
Source Code:
series.py
# write the code..
a=int(input('a: '))
b=int(input('b: '))
2023-2027-ECE-B
N=int(input('N: '))
print('result: ',end='')
for i in range (1,N+1):
print(a+pow(b,i),end=' ')
User Output
a:
3
b:
2
N:
3
result: 5 7 11
Test Case - 2
User Output
a:
4
b:
3
N:
5
result: 7 13 31 85 247
S.No: 15 Exp. Name: Area of the Pyramid Date: 2024-10-25
Aim:
Humpty and Dumpty both went to Egypt to explore the Pyramids. On the site of the pyramids, Humpty saw a
Page No: 25
unique pyramid and asked Dumpty what's the area of this pyramid. Dumpty has no idea about it. Can you help
Dumpty with this?
Functional Description:
Area = (height * base) / 2
ID: 249X5A04L9
Constraints:
• height and base must be >= 1
• Display the area computed upto 3 decimal places (Precision)
areaofpyramid.py
2023-2027-ECE-B
# write your code here...
a=float(input("b: "))
b=float(input("h: "))
A=(a*b/2)
print("Area:",end=" ")
print(f"{A:.3f}")
User Output
b:
31.5
h:
43.7
Area: 688.275
Test Case - 2
User Output
b:
8.2
h:
10.63
Area: 43.583
S.No: 16 Exp. Name: Applications of Loops Date: 2024-10-25
Aim:
Write a Python program that prints the right-angled triangle pattern as shown in the example. This program
Page No: 26
prompts the user to input an integer, which in turn determines the number of rows in the pattern
Example:
If the given integer is 5, then the pattern would be
*
ID: 249X5A04L9
* *
* *
* *
* * * * *
Input format:
• The input is the integer that represents the number of rows in the pattern.
Output format:
• The output is the pattern that resembles the pattern as shown above.
Source Code:
2023-2027-ECE-B
print_pattern.py
rows=int(input())
for i in range(1,rows):
for j in range(0,i):
if j==0 or j==i-1:
print("*",end=" ")
else:
User Output
5
*
* *
* *
* *
* * * * *
Test Case - 2
User Output
8
*
*
*
*
*
* *
*
*
*
*
*
* * * * * * * *
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 27
S.No: 17 Exp. Name: Perfect Roll number Date: 2024-10-25
Aim:
In a group of students, everyone has a unique roll number. One day they are willing to find the students who
Page No: 28
have the perfect roll numbers.
They need your assistance to determine whether the given roll number is the perfect number or not. Can you
assist them by writing a program in Python?
ID: 249X5A04L9
Note: A perfect Number is a number for which the sum of its positive divisors (excluding itself) is equal to the
number itself.
Constraints:
Roll Number must be a positive integer.
Input Format:
The input line reads an integer representing a roll number.
Output Format:
The output line prints whether the given roll number is a perfect number or not.
Source Code:
2023-2027-ECE-B
PerfectRollNumber.py
def is_perfect_number(number):
# write your code here...
c=0
for i in range(1,number):
roll_number = int(input())
if is_perfect_number(roll_number):
print("Perfect number")
else:
print("Not a perfect number")
User Output
6
25
User Output
Perfect number
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 29
S.No: 18 Exp. Name: Function with multiple return values Date: 2024-10-25
Aim:
Write a Python program that defines a function with multiple return values to calculate sum, mean and maximum
Page No: 30
of the given list of numbers.
Input Format:
• A list of space-separated integers.
ID: 249X5A04L9
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
Constraints:
• 0 < length of the list <= 100
Source Code:
multiplefun.py
def calculate_stats(numbers):
2023-2027-ECE-B
total_sum=sum(numbers)
mean=round(total_sum/len(numbers),2)
max_value=max(numbers)
print(total_sum)
print(mean)
print(max_value)
numbers=list(map(int,input().split()))
User Output
12 23 34 45 56 67 78 89
404
50.5
89
Test Case - 2
User Output
-23 -45 -56 -90 -12 -87
-313
-52.17
-12
S.No: 19 Exp. Name: Default Arguments Function Date: 2024-10-25
Aim:
Write a program to define a function using default arguments.
Page No: 31
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
ID: 249X5A04L9
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}.
Source Code:
default.py
# Define a function with default arguments
def greet(name,age,country):
2023-2027-ECE-B
print(f"Hello, {name}! You are {age} years old and you are from {country}")
User Output
-1 for default:
-1
-1 for default:
-1
-1 for default:
-1
Hello, Dude! You are 0 years old and you are from Space
Test Case - 2
User Output
-1 for default:
Ram
-1 for default:
-1
-1 for default:
Page No: 32
-1
Hello, Ram! You are 0 years old and you are from Space
Test Case - 3
ID: 249X5A04L9
User Output
-1 for default:
Vikas
-1 for default:
26
-1 for default:
America
Hello, Vikas! You are 26 years old and you are from America
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 20 Exp. Name: Length of the String Date: 2024-10-25
Aim:
Write a program to find the length of the string without using any libraryfunctions.
Page No: 33
Input Format:
A single line containing a string s.
Output Format:
ID: 249X5A04L9
A single integer representing the length of the input string.
Source Code:
length.py
def string_length(s):
c=0
for i in s:
c+=1
return c
s=str(input())
print(string_length(s))
2023-2027-ECE-B
Execution Results - All test cases have succeeded!
Test Case - 1
Test Case - 2
User Output
Hello@World!!
13
Test Case - 3
User Output
12345678
8
S.No: 21 Exp. Name: Count of Substring in given string Date: 2024-10-25
Aim:
The user enters a string and a substring. You have to print the number of times that the substring occurs in the
Page No: 34
given string. String traversal will take place from left to right, not from right to left.
Constraints:
• 1 <= len(string) <=200.
• Each character in the string is an ASCII character.
ID: 249X5A04L9
Input Format:
• The first line of input contains the main string.
• The second line contains the substring.
Output Format:
• Output is an integer representing the total number of occurrences of the substring in the main string.
Source Code:
SubstringCount.py
2023-2027-ECE-B
# Type Content here...
def count_substring_occurence(main_string,sub_string):
count=0
sub_len=len(sub_string)
for i in range(len(main_string) - sub_len+1):
if main_string[i:i+sub_len]==sub_string:
count+=1
User Output
ABCDCDC
CDC
2
Test Case - 2
User Output
CodeTantra
co
0
S.No: 22 Exp. Name: List operations Date: 2024-10-26
Aim:
Write a program to perform the following operations on a list.
Page No: 35
i. Addition
ii. Insertion
iii. Slicing
Input Format:
ID: 249X5A04L9
• The first line should take space-separated integers to form the list.
• The second line of input should prompt the user to enter two integers separated by a space representing
the key and value for the insertion.
• The third line should take space-separated start index and end index for slicing.
Output Format:
• First line should display the initial list.
• Second line should display the list after insertion.
• Third line should display the list after slicing.
Example 1:
Input:
2023-2027-ECE-B
12345
05
03
Output
[1, 2, 3, 4, 5]
[5, 1, 2, 3, 4, 5]
Note:
• In Python, adding an element with append adds it to the end of a list. To insert an element at a specific
index, insert operation need to be used.
Source Code:
listOp.py
#Type Content here.
a=list(map(int, input().split()))
b=list(map(int, input().split()))
c=list(map(int,input().split()))
print(a)
a.insert(b[0],b[1])
print(a)
a=a[c[0]:c[1]]
print(a)
User Output
12345
05
03
[1, 2, 3, 4, 5]
[5, 1, 2, 3, 4, 5]
[5, 1, 2]
Page No: 36
Test Case - 2
User Output
ID: 249X5A04L9
12 52 65 41 23 89 654
7 485
08
[12, 52, 65, 41, 23, 89, 654]
[12, 52, 65, 41, 23, 89, 654, 485]
[12, 52, 65, 41, 23, 89, 654, 485]
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 23 Exp. Name: Demonstration of Working with Lists Date: 2024-10-26
Aim:
Write a program to demonstrate working with lists in python.
Page No: 37
Sample Test Case:
Input:
Enter a list of elements (separated by commas): 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
ID: 249X5A04L9
Output:
List of elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Length of list: 10
Minimum value: 1
Maximum value: 10
Sum of values: 55
Sorted list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Source Code:
list.py
2023-2027-ECE-B
#Type Content here...
N=list(map(int,input('Enter a list of elements (separated by commas): ').split(',')))
print('List of elements:',N)
print('Length of list:',len(N))
print('Minimum value:',min(N))
print('Maximum value:',max(N))
print('Sum of values:',sum(N))
User Output
Enter a list of elements (separated by commas):
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
List of elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Length of list: 10
Minimum value: 1
Maximum value: 10
Sum of values: 55
Sorted list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Test Case - 2
User Output
Enter a list of elements (separated by commas):
3, 8, 2, 9, 5
List of elements: [3, 8, 2, 9, 5]
Maximum value: 9
Minimum value: 2
Sum of values: 27
Sorted list: [2, 3, 5, 8, 9]
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 38
S.No: 24 Exp. Name: List of Odd squares Date: 2024-10-26
Aim:
The given Python program defines two functions odd_checker and square_list, both functions take the list as the
Page No: 39
argument
square_list: This function squares each element of the list that has passed and returns the list of squares.
odd_checker: This function filters out the odd numbers from the list that has passed and returns a list of odd
numbers.
ID: 249X5A04L9
Your task is to write the required logic in the function's body in accordance with the functionalities given.
Input format:
• The input is the list of integers separated by comma(,)
Output format:
• The output is the list of integers that represents a list of squared odd numbers from the input list.
Note: For simplicity, the code for reading input & printing output has already been given. You just need to fill the
code in the body of the functions given.
Source Code:
2023-2027-ECE-B
func_comp.py
def odd_checker(lst):
b=[]
for i in range (0,len(lst)):
if lst[i]%2==1:
input_lst = list(map(int,input().split(",")))
print(odd_checker(square_list(input_lst)))
User Output
1,2,3,4,5,6
[1, 9, 25]
Test Case - 2
User Output
[81, 121]
-6,-9,-10,-11
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 40
S.No: 25 Exp. Name: Chocolate Distribution Date: 2024-10-26
Aim:
Complete the given Python function order_chocolate that takes two integer arguments, n (Number of
Page No: 41
chocolates) and m (Number of students).
The function is designed to distribute chocolates among students. It checks whether it's possible to evenly
distribute n chocolates among m students. If it's possible, the function returns 0. If it's not possible to evenly
distribute the chocolates, the function calculates the minimum number of extra chocolates needed to make the
ID: 249X5A04L9
distribution even and returns that number.
Hint:
• When you divide n by m if you have 0 remainder, then it is possible to distribute evenly.
• Otherwise, you can take away the remainder from the number of students.
Input format:
• The first line of the input is an integer that represents the number of chocolates.
• The second line of the input is an integer that represents the number of students.
Output format:
• If the number of students entered is a positive integer greater than zero, then output the minimum integer
2023-2027-ECE-B
representing the number of chocolates needed to evenly distribute among them otherwise print "Invalid".
Note: For simplicity, the code for reading input & printing output has already been given. You just need to fill the
code in the function body given.
Source Code:
order_chocolate.py
chclts = int(input())
stdnts = int(input())
print(order_chocolate(chclts,stdnts))
User Output
78
8
2
Test Case - 2
User Output
85
6
Page No: 42
5
Test Case - 3
ID: 249X5A04L9
User Output
9
3
0
Test Case - 4
User Output
25
2023-2027-ECE-B
0
Invalid
Aim:
In the ancient city of Arithmetica, a unique method of encoding messages has been discovered, involving a
Page No: 43
special mathematical technique. The encoded messages require finding the product between pairs of numbers in
a given list and then determining the maximum product achievable. Your task is to create a Python program to
decipher these messages by finding and displaying the largest product that can be obtained by multiplying any
two numbers from the provided list.
ID: 249X5A04L9
Input Format:
The first line contains space-separated positive integers representing the elements of the list.
Output Format:
The output is the integer that represents the maximum product achievable by multiplying any two numbers from
the given list.
Constraints:
The elements of the list must be positive.
Example:
Input: 18 5 12 8 3
2023-2027-ECE-B
Output: 216
Explanation:
In the list [18, 5, 12, 8, 3], the maximum product is obtained by multiplying 18 and 12, resulting in 216.
Note:
For simplicity, the code for taking input and printing output is provided to you in the editor. You just need to fill
maxproduct.py
def find_max_product(nums):
a=nums
a.sort()
b=a[-1]*a[-2]
return b
input_numbers = input()
numbers_list = list(map(int, input_numbers.split()))
result = find_max_product(numbers_list)
print(result)
User Output
12345
20
216
18 5 12 8 3
User Output
Test Case - 2
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 44
Exp. Name: Product of maximum and minimum
S.No: 27 Date: 2024-10-26
palindrome numbers in given list
Aim:
Page No: 45
In a small town named Palindromia, there's a coding event going on. The challenge in the event is to find and
showcase the product of the maximum and minimum palindrome numbers from a list of numbers.
ID: 249X5A04L9
Input Format:
• The input line reads space-separated integers.
Output Format:
• The output is an integer representing the product of maximum and minimum palindrome numbers. If
there are no palindrome numbers in the given list, print "0" (zero).
Note: If there is only one palindromic number in the list, it will be considered both the maximum and minimum
palindromic number. In such cases, the product of the maximum and minimum palindromic numbers will be the
square of that single palindromic number.
Source Code:
2023-2027-ECE-B
Min_max_palindrome_product.py
def is_palindrome(num):
return str(num)==str(num)[::-1]
def find_palindrome_product(numbers):
palindromes=[num for num in numbers if is_palindrome(num)]
if not palindromes:
User Output
121 15 78 11
1331
Test Case - 2
User Output
95 48 74 621 35
0
S.No: 28 Exp. Name: Tuple Creation Date: 2024-10-26
Aim:
Write a Python program that prompts the user to enter details for two members and creates tuples for each
Page No: 46
member consisting of (name(string), age(int), address(string), college(string)). Concatenate these tuples into a
single tuple and print the concatenated tuple.
Input Format:
• The first line should take user input with Name, Age, Address, College as space-separated values for
ID: 249X5A04L9
Member 1.
• The second line should take user input with Name, Age, Address, College as space-separated values for
Member 2.
Output Format:
• In the first line print the tuple for Member 1.
• Print the tuple for Member 2 in the next line.
• Finally, print the concatenated tuple of both members.
Example1:
Input:
2023-2027-ECE-B
John 12 Tampa St.Joseph
Jane 15 Florida St.Mary
Output:
('John',·'12',·'Tampa',·'St.Joseph') // Member 1
('Jane',·'15',·'Florida',·'St.Mary') // Member 2
('John',·'12',·'Tampa',·'St.Joseph',·'Jane',·'15',·'Florida',·'St.Mary') // Concatenated Tuple
stdTup.py
a=input()
b=input()
n1,a1,ad1,c1=a.split()
t1=(n1,int(a1),ad1,c1)
n2,a2,ad2,c2=b.split()
t2=(n2,int(a2),ad2,c2)
print(t1)
print(t2)
print(t1+t2)
User Output
John 12 Tampa St.Joseph
Jane 15 Florida St.Mary
('John', 12, 'Tampa', 'St.Joseph')
('Jane', 15, 'Florida', 'St.Mary')
('John', 12, 'Tampa', 'St.Joseph', 'Jane', 15, 'Florida', 'St.Mary')
Test Case - 2
User Output
Ram 22 Delhi IITDelhi
Varun 24 Mumbai NITWarangal
Page No: 47
('Ram', 22, 'Delhi', 'IITDelhi')
('Varun', 24, 'Mumbai', 'NITWarangal')
('Ram', 22, 'Delhi', 'IITDelhi', 'Varun', 24, 'Mumbai', 'NITWarangal')
ID: 249X5A04L9
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 30 Exp. Name: Vowel Counter Date: 2024-10-25
Aim:
Write a Python program to count the number of vowels in a given string without using control flow statements.
Page No: 48
Input Format:
The program should prompt the user to enter a string.
Output Format:
ID: 249X5A04L9
Display the number of vowels present in the entered string.
Source Code:
vowel.py
def count_vowels(s):
2023-2027-ECE-B
Execution Results - All test cases have succeeded!
Test Case - 1
Test Case - 2
User Output
CodeTantra
4
Test Case - 3
User Output
Python Programming
4
Exp. Name: Program to check if Key exists in
S.No: 31 Date: 2024-10-26
Dictionary
Aim:
Page No: 49
Write a Python program that checks if a given key exists in a dictionary.
Input Format:
• First line of input contains space separated strings that represents keys of a dictionary
• Second line contains space separated strings that represents values of a dictionary
ID: 249X5A04L9
• Third line contains the key (as a string) to check whether it is present in the dictionary or not.
Output Format:
• The first line of the output should print the dictionary.
• Next it should print "Exist" if key is present in the dictionary or print "Does not Exist" if key is not present in
the dictionary and if the length of keys does not match with length of values then print "Invalid" .
Refer to shown test cases to match with input and output format.
Source Code:
keyExist.py
2023-2027-ECE-B
k=input().split()
v=input().split()
if len(k)!=len(v):
print('Invalid')
else:
k_c=input()
d=dict(zip(k,v))
User Output
12345
ABCDE
5
{'1': 'A', '2': 'B', '3': 'C', '4': 'D', '5': 'E'}
Exist
Test Case - 2
User Output
10 20 30 40 50 60 70 80
Ten Twenty Thirty Forty Fifty Sixty
Test Case - 3
User Output
John Reena Sara David
24 32 18 41
Page No: 50
Jane
{'John': '24', 'Reena': '32', 'Sara': '18', 'David': '41'}
Does not Exist
ID: 249X5A04L9
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 32 Exp. Name: Add Key Value Pair to Dictionary Date: 2024-10-26
Aim:
Write a Python program that adds a new key-value pair to an existing dictionary.
Page No: 51
Input Format:
• The first line contains space-separated strings that represent the keys of a dictionary.
• The second line contains space-separated strings that represent the values of the dictionary.
• The third line contains two space-separated strings that represent the new key and value to be added to
ID: 249X5A04L9
the existing dictionary.
Output Format:
• First line should display the original dictionary before adding the new key-value pair.
• Second line should display the updated dictionary after adding the new key-value pair.
Note: If the number of keys and values does not match, display "Invalid".
Source Code:
keyValue.py
k=input().split()
2023-2027-ECE-B
v=input().split()
if len(k)==len(v):
nk,nv=input().split()
d=dict(zip(k,v))
print(d)
d[nk]=nv
print(d)
User Output
Mobile Laptop Adopter Headset
10000 50000 2000
Invalid
Test Case - 2
User Output
thirty fifty seventy ninety forty eighty
30 50 70 90 40 80
four 4
{'thirty': '30', 'fifty': '50', 'seventy': '70', 'ninety': '90', 'forty': '40', 'eighty':
'80'}
{'thirty': '30', 'fifty': '50', 'seventy': '70', 'ninety': '90', 'forty': '40', 'eighty':
'80', 'four': '4'}
S.No: 33 Exp. Name: Sum of all items in the dictionary Date: 2024-10-26
Aim:
Write a program that allows the user to create a dictionary by entering key-value pairs. Calculate and print the
Page No: 52
sum of all values in the dictionary.
Input Format:
To populate this dictionary, prompt the user to enter an integer indicating the size of the dictionary.
For each key-value pair:
ID: 249X5A04L9
• Prompt the user to enter a key (string).
• Prompt the user to enter a value (integer).
Output Format:
• The output should display the sum of the values in the dictionary formatted as follows: "Sum: <the value
after adding the values>".
sumOfValues.py
2023-2027-ECE-B
a=int(input('size:'))
d={}
for i in range(a):
k=input('key:')
v=int(input('value:'))
d[k]=v
s=sum(d.values())
User Output
size:
1
key:
ninety
value:
90
Sum:90
Test Case - 2
User Output
size:
4
key:
five
6
5
60
12
six
key:
key:
key:
sixty
twelve
Sum:83
value:
value:
value:
value:
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 53
S.No: 34 Exp. Name: Sorting the key-value pairs Date: 2024-10-26
Aim:
Hitler's junior brother Pitler is a Grammer nazi and he wants everything in order. One day he ordered you to
Page No: 54
develop a program that accepts the serial number and name of the soldier as dictionary key-value pairs and to
print the sorted details depending on the serial number.
ID: 249X5A04L9
Input Format:
The first line reads an integer representing the number of soldiers.
The next lines read an integer and a string representing the serial number and name of the soldier.
Output Format:
The output is a sorted dictionary.
Source Code:
SortedDictbyKeys.py
n = int(input())
my_dict = {}
2023-2027-ECE-B
for i in range(n):
key=int(input())
value=input()
my_dict[key]=value
a=dict(sorted(my_dict.items()))
print(a)
User Output
3
512
Rakesh
325
Arjun
408
Jay
{325: 'Arjun', 408: 'Jay', 512: 'Rakesh'}
Test Case - 2
User Output
0
{}
S.No: 35 Exp. Name: Manage birthdays Date: 2024-10-26
Aim:
Write a Python program that manages your friends' birthdays using a dictionary:
Page No: 55
1. Initialize a dictionary where the keys are your friends' names and the values are their birthdays.
2. Print the items in the dictionary in the sorted order of the names.
3. Prompt the user to enter a name and check if it is present in the dictionary. If the name is not found,
prompt the user to enter the birthday and add it to the dictionary.
ID: 249X5A04L9
Note: Refer to the displayed test cases for better understanding.
Source Code:
birthdaydict.py
# Input names and birthdays
names = input("Names: ").split(' ')
birthdays = input("Birthdays: ").split(' ')
2023-2027-ECE-B
sorted_dict = dict(sorted(bd_dict.items()))
# Print sorted dictionary
for name, bday in sorted_dict.items():
print(f"{name}: {bday}")
while True:
n_t_c=input("Name to check (or 'quit' to exit): ")
if n_t_c=='quit':
User Output
Names:
Swathi Sangeetha Samatha
Birthdays:
20/09/2001 07/03/2005 11/04/2007
Samatha: 11/04/2007
Sangeetha: 07/03/2005
Swathi: 20/09/2001
Name to check (or 'quit' to exit):
Aanya
Name not found
Birthday to add:
Page No: 56
27/10/2022
Added to dictionary
Name to check (or 'quit' to exit):
Samatha
ID: 249X5A04L9
Birthday: 11/04/2007
Name to check (or 'quit' to exit):
quit
Final dictionary:
Aanya: 27/10/2022
Samatha: 11/04/2007
Sangeetha: 07/03/2005
Swathi: 20/09/2001
Test Case - 2
2023-2027-ECE-B
User Output
Names:
John Doe Tina Mary
Birthdays:
01/01/2000 15/02/1998 29/08/1992
30/06/1999
Aim:
Develop a program to sort the contents of a text file and write the sorted contents into a separate text file and
Page No: 57
print the output.
[Hint: Use string methods strip(), len(), list methods sort(), append(), and file methods open(), read lines(), and
write()].
ID: 249X5A04L9
Note: The output file should have only lower-case words, so any upper-case words from source must be lowered.
Refer to shown test cases to match with the input and output format.
Source Code:
sortLower.py
def sort_file_contents(input_file):
try:
with open(input_file,'r')as file:
lines=[line.strip().lower() for line in file.readlines()]
lines.sort()
2023-2027-ECE-B
for line in lines:
print(line)
except FileNotFoundError:
print("File not found")
input_file=input()
sort_file_contents(input_file)
file2.txt
aim
air
at
input.txt
Insert
text
here
orange
banana
file1.txt
output.txt
User Output
User Output
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 58
S.No: 37 Exp. Name: File Reverse Date: 2024-10-28
Aim:
Sara is developing a tool that manipulates the text files efficiently. Your task is to assist Sara to create a Python
Page No: 59
program that reads a text file and prints each line in reverse order.
Input Format:
• The program should prompt the user to enter the file name
ID: 249X5A04L9
Output Format:
• If the entered file is found then it should display the lines of the files in reverse order otherwise "File not
found".
Source Code:
reverse.py
def reverse(filename):
try:
with open(filename,'r') as file:
lines=file.readlines()
for line in lines:
2023-2027-ECE-B
print(line.strip()[::-1])
except FileNotFoundError:
print("File not found")
filename=input()
reverse(filename)
input.txt
This
Is
Coding
Platform
file2.txt
CodeTantra
Tech
Solutions
User Output
User Output
Test Case - 2
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 60
Exp. Name: Count the sentences, words and
S.No: 38 Date: 2024-10-28
characters in a file
Aim:
Page No: 61
Write a Python program that reads a file and prints the number of lines, words, and characters.
Input Format:
• The input will be a single string, which is the name of the file to be read.
ID: 249X5A04L9
Output Format:
The output will be three separate lines, each containing a count:
• The first line will contain the number of lines in the file, prefixed with "Sentences: ".
• The second line will contain the number of words in the file, prefixed with "Words: ".
• The third line will contain the number of characters in the file, prefixed with "Chars: ".
Source Code:
Count.py
fp = input("file name:")
def count_file_contents(input_file):
try:
2023-2027-ECE-B
with open(input_file ,'r') as file:
lines=file.readlines()
num_lines=len(lines)
num_words=sum(len(line.split()) for line in lines)
num_chars=sum(len(line) for line in lines)
print(f'Sentences: {num_lines}',)
print(f'Words: {num_words}',)
input1.txt
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Everything matters.
input2.txt
CodeTantra
Start coding in 60 mins
Page No: 62
test3.txt
Count the sentences in the file.
Count the words in the file.
Count the characters in the file.
ID: 249X5A04L9
test2.txt
Hydrofoil is an underwater fin with a falt or curved wing-like
surface that is designed to lift a moving boat or ship
by means of the reaction upon its surface
2023-2027-ECE-B
Test Case - 1
User Output
file name:
input1.txt
Sentences: 8
Test Case - 2
User Output
file name:
input2.txt
Sentences: 7
Words: 51
Chars: 306
S.No: 39 Exp. Name: Array Operations Date: 2024-10-28
Aim:
Write a Python program to create an array of strings entered by the user and perform the following operations
Page No: 63
sequentially:
ID: 249X5A04L9
• Reverse the order of items in the array.
Input Format:
• First line contains space-separated string values to initialize the array.
• Second line contains a single string to append to the array.
• Third line contains an integer representing the position at which to insert the value.
• Fourth line contains a single string value to insert into the array.
Output Format:
• Display the created array.
• Display the array after appending the value.
• Display the array after inserting the value at the specified position.
2023-2027-ECE-B
• Display the reversed array.
Note: The index position to insert the value should be less than or equal to the length of the array. Otherwise
print "Invalid position".
Refer to shown test cases to match the input and output format with the test cases.
Source Code:
User Output
12 23 34 45 56 67
85
2
69
['12', '23', '34', '45', '56', '67']
['12', '23', '34', '45', '56', '67', '85']
Page No: 64
['12', '23', '69', '34', '45', '56', '67', '85']
['85', '67', '56', '45', '34', '69', '23', '12']
Test Case - 2
ID: 249X5A04L9
User Output
abcdefgh
k
5
o
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k']
['a', 'b', 'c', 'd', 'e', 'o', 'f', 'g', 'h', 'k']
['k', 'h', 'g', 'f', 'o', 'e', 'd', 'c', 'b', 'a']
2023-2027-ECE-B
Test Case - 3
User Output
hi hello how are you
fine
Aim:
Write a Python program to add two matrices. First, prompt the user to input the dimensions of two matrices (r1,
Page No: 65
c1) for the first matrix and then allow the user to input the elements of each matrix. Then prompt the user to
enter dimensions (r2, c2) for the second matrix and allow the user to enter elements. If the matrices have
compatible dimensions (r1 == r2 and c1 == c2), compute their sum; otherwise, indicate that matrix addition is
not possible due to incompatible dimensions.
ID: 249X5A04L9
Input Format:
• First line contains two space separated integers representing number of rows and columns for matrix1
• Next, R1 lines contains C1 number of integers separated by space representing the elements of matrix 1
• Next line contains two space separated integers representing number of rows and columns for matrix2
• Next, R2 lines contains C2 number of integers separated by space representing the elements of matrix 2
Output Format:
• If the matrices have compatible dimensions (r1 == r2 and c1 == c2), print the sum of corresponding
elements of the matrices otherwise print "Invalid".
Source Code:
matrix.py
2023-2027-ECE-B
#Type Content here...
def read_matrix(rows,cols):
matrix=[]
for i in range(rows):
row=list(map(int,input().split()))
matrix.append(row)
User Output
23
123
456
23
789
23
23
12
22
023
123
012
4 6 8
Invalid
8 10 12
User Output
Test Case - 2
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 66
S.No: 41 Exp. Name: Matrix Multiplication Date: 2024-10-30
Aim:
Write a Python function matrix_multiplication() that performs matrix multiplication of two matrices and prints the
Page No: 67
resulting matrix. If the matrices cannot be multiplied, the function should print an appropriate error message.
Input Format:
• The dimensions of the first matrix (r1 c1), where r1 is the number of rows and c1 is the number of columns.
• The elements of the first matrix, provided row by row.
ID: 249X5A04L9
• The dimensions of the second matrix (r2 c2), where r2 is the number of rows and c2 is the number of
columns.
• The elements of the second matrix, provided row by row.
Output Format:
Print the resulting matrix after multiplication, where each element of the matrix is separated by a space otherwise
print "Invalid".
Note: Number of columns of first matrix must be equal to number of rows of second matrix for matrix
multiplication.
Source Code:
2023-2027-ECE-B
matrixmul.py
User Output
23
123
456
34
1234
5678
9012
38 14 20 26
83 38 53 68
Page No: 68
Test Case - 2
User Output
ID: 249X5A04L9
22
-3 4
4 -7
22
-4 5
-6 7
-12 13
26 -29
2023-2027-ECE-B
Test Case - 3
User Output
22
6 12
-3 7
Aim:
Write a Python program that defines a base class Shape with two methods, area and perimeter, that are meant to
Page No: 69
be overridden by subclasses. Define three subclasses: Circle, Triangle, and Square, each of which implements the
area and perimeter methods. The program should then create instances of these subclasses based on user input
and print their areas and perimeters, rounded to two decimal places.
Input Format:
ID: 249X5A04L9
• The first line contains a single float representing the radius of a circle.
• The second line contains three space-separated floats representing the sides of a triangle.
• The third line contains a single float representing the side length of a square.
Output Format:
• Print the area and perimeter of the circle on one line, separated by a space, rounded to two decimal places.
• Print the area and perimeter of the triangle on the next line, separated by a space, rounded to two decimal
places.
• Print the area and perimeter of the square on the last line, separated by a space, rounded to two decimal
places.
Note:
2023-2027-ECE-B
• Triangle sides must satisfy the triangle inequality theorem: the sum of any two sides must be greater than
the third side, ensuring the formation of a valid triangle.
• Area of traingle ABC = √[s × (s – a) × (s – b) × (s – c)]
• s = (side1 + side2 + side3) / 2
Source Code:
geometry1.py
Page No: 70
pass
class Circle(Shape ):
def __init__(self,radius):
self.radius = radius
def area(self):
ID: 249X5A04L9
return math.pi*self.radius**2
def perimeter(self):
return 2*math.pi*self.radius
# Triangle subclass
class Triangle(Shape ):
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
def area(self):
k=(self.a+self.b+self.c)/2
return (k*(k-self.a)*(k-self.b)*(k-self.c))**(0.5)
2023-2027-ECE-B
def perimeter(self):
return(self.a+self.b+self.c)
# Square subclass
class Square(Shape ):
def __init__(self,side):
self.side = side
def area(self):
User Output
12
456
4
452.39 75.40
9.92 15.00
16.00 16.00
7.5
5.0
3.0 4.0 5.0
6.00 12.00
56.25 30.00
78.54 31.42
User Output
Test Case - 2
G Pulla Reddy Engineering College (Autonomous) 2023-2027-ECE-B ID: 249X5A04L9 Page No: 71
S.No: 44 Exp. Name: Codeathon Competition Date: 2024-10-29
Aim:
Define a base class Codeathon with the following specifications:
Page No: 72
• The class should have a constructor that takes three parameters (year, coordinator, and university)
representing the details of a Codeathon competition.
• In the constructor, initialize instance variables year, coordinator, and university with the provided values.
• Implement a method named details in the Codeathon class. The details method should return a string
containing the details (year, coordinator, and university) of the Codeathon.
ID: 249X5A04L9
Now, create a child class named Champion that inherits from the Codeathon class with the following
specifications:
• In the Champion class, override the details method to return the details of the Codeathon.
Input Format:
The input consists of three lines, each containing relevant information about a Codeathon competition (year,
coordinator, and university).
Output Format:
The output is a string that includes details about the Codeathon.
2023-2027-ECE-B
Note: The code for handling inputs, creating objects, invoking methods, and printing results is already provided
in the editor. Your task is to implement the Codeathon class and the child class Champion based on the given
specifications.
Source Code:
Codeathon.py
# Inputs
year = int(input())
coordinator = input()
university = input()
# Display details
print(champion_instance.details())
Page No: 73
2022, John Doe, Lovely Professional University
Test Case - 2
ID: 249X5A04L9
User Output
2005
Arora
Stanford University
2005, Arora, Stanford University
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 45 Exp. Name: Line in a file Date: 2024-10-29
Aim:
Ashraf, a computer science student, is passionate about books and technology. He envisions creating an online
Page No: 74
library management system that will revolutionize how users access and manage their book collections. As part of
his project, Ashrif has prepared several files containing lists of book titles, each representing a different category
or genre.
As part of his project development, Ashrif has created a Python program that prompts users to enter the name of
ID: 249X5A04L9
a file containing a list of book titles and an alphabetical character. The program then searches the file for a line
starting with the specified character and prints out the book title if found. If no book title starting with the
specified character is found, the program prints "Not found".
Input format:
• The first line is the file name.
• The second line is the alphabetical character.
Output format:
• The output is the line in the file starting with the user-given character otherwise displays "Not found".
2023-2027-ECE-B
Source Code:
lineinfile.py
# write your code here..
def find_book_by_character(filename,char):
try:
file1.txt
file2.txt
Harry Potter and the Sorcerer's Stone
The Great Gatsby
To Kill a Mockingbird
Pride and Prejudice
The Catcher in the Rye
Page No: 75
Execution Results - All test cases have succeeded!
ID: 249X5A04L9
Test Case - 1
User Output
file1.txt
S
Sapiens: A Brief History of Humankind
Test Case - 2
User Output
2023-2027-ECE-B
file1.txt
F
Not found
Aim:
Create a scatter plot to visualize the relationship between two columns from a dataset represented as a
Page No: 76
dictionary. Convert the dictionary into a Pandas DataFrame for this purpose.
Input Format:
• Prompt the user to input two column names (strings) separated by space.
ID: 249X5A04L9
Output Format:
• Display a scatter plot showing the relationship between the selected columns.
• Ensure the plot includes appropriate labels, title, legend, grid, and customization (such as color and marker
style).
Plot Settings:
• Use blue color to set the color of the markers
• Marker Style: Use marker='o' to set the marker style
• Use "Scatter" as label for the scatter plot in the legend.
• Set "Scatter Plot" as the title of the plot.
• Use column1 and column2 as the labels for the x-axis and y-axis, respectively.
• Display the legend.
2023-2027-ECE-B
• Display the grid on the plot for better visualization.
Note: Refer to the data set that has been provided to you in the editor.
Source Code:
scatter.py
# Given DataFrame
std_marks = {
'A': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
'B': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'C': [11, 22, 33, 44, 55, 66, 77, 88, 99, 101],
'D': [103, 105, 109, 114, 125, 135, 149, 154, 162, 185],
'E': [52, 86, 75, 41, 32, 71, 68, 94, 73, 69]
}
df = pd.DataFrame(std_marks)
column1,column2 = input().split()
if column1 in df.columns and column2 in df.columns:
plt.scatter(df[column1],df[column2],color = 'blue', label = 'Scatter')
plt.title('Scatter plot')
plt.xlabel(column1)
plt.ylabel(column2)
plt.legend()
plt.grid('true')
plt.show()
User Output
AC
data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAOXRFWHRTb2Z0d2FyZQBNYX
Page No: 77
Test Case - 2
ID: 249X5A04L9
User Output
BD
data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAOXRFWHRTb2Z0d2FyZQBNYX
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 48 Exp. Name: Numpy Array Date: 2024-10-29
Aim:
Write a Python program that prompts the user to enter elements for a NumPy array. The program should create a
Page No: 78
NumPy array using the entered elements and display it. Assume all input elements are valid numeric values.
Input Format:
• The program expects the user to enter elements of the array separated by spaces.
ID: 249X5A04L9
Output Format:
• The program should output the NumPy array created from the user's input.
Source Code:
arrayNumpy.py
import numpy as np
a=list(map(int,input().split()))
array=np.array(a)
print(array)
2023-2027-ECE-B
Execution Results - All test cases have succeeded!
Test Case - 1
Test Case - 2
User Output
10 20 30 40 50 60 70 80 90
[10 20 30 40 50 60 70 80 90]
Test Case - 3
User Output
-1 -2 -3 -4 5 6 7 8
[-1 -2 -3 -4 5 6 7 8]
S.No: 49 Exp. Name: Numpy array operations Date: 2024-10-29
Aim:
Write a python program to demonstrate the usage of ndim, shape and size for a Numpy Array. The program
Page No: 79
should create a NumPy array using the entered elements and display it. Assume all input elements are valid
numeric values.
Input Format:
• User inputs the number of rows and columns with space separated values.
ID: 249X5A04L9
• 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.
Source Code:
numpyarr.py
import numpy as np
2023-2027-ECE-B
rows,c = list(map(int,input().split()))
elements = []
for _ in range(rows):
row = list(map(int,input().split()))
elements.append(row)
array = np.array(elements)
print(array)
User Output
34
1234
5678
9 10 11 12
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
2
(3, 4)
12
Test Case - 2
User Output
00
[]
Page No: 80
2
(0, 0)
0
ID: 249X5A04L9
Test Case - 3
User Output
23
10 20 30
40 50 60
[[10 20 30]
[40 50 60]]
2
(2, 3)
2023-2027-ECE-B
6
Aim:
Write a Python program that prompts the user to enter elements for a NumPy array. The program should
Page No: 81
compute and print the minimum value, maximum value and sum of elements of the array using NumPy functions.
Input Format:
• The program expects the user to enter elements of the array separated by spaces.
ID: 249X5A04L9
Output Format:
• First display the original NumPy array entered by the user.
• Next, print the minimum value found in the array.
• Then, show the maximum value present in the array.
• Lastly, display the sum of all elements within the array.
Source Code:
arrayStat.py
import numpy as np
elements=list(map(int,input().split()))
array=np.array(elements)
2023-2027-ECE-B
print(array)
print(np.min(array))
print(np.max(array))
print(np.sum(array))
User Output
123456789
[1 2 3 4 5 6 7 8 9]
1
9
45
Test Case - 2
User Output
-10 -20 -30 -40 -50
[-10 -20 -30 -40 -50]
-50
-10
-150
Exp. Name: Numpy, pandas operations using
S.No: 51 Date: 2024-11-07
dictionary
Aim:
Page No: 82
Convert the given dataset into a Pandas DataFrame representing students (A, B, C, D, E) and their marks in ten
different subjects. Each student's data is structured as follows:
ID: 249X5A04L9
Define a function that allows the user to perform a custom data selection operation on this DataFrame. The
function should:
• Take user input for the student's name (column) and a minimum marks threshold (condition_value).
• Apply the head() function to display the initial rows of the DataFrame.
• Filter and display the rows (students) whose marks in the specified subject (column) are greater than the
provided threshold (condition_value).
Input Format:
• Prompt the user to input the student's name (A, B, C, D, E).
• Prompt the user to input the minimum marks they want to filter by in the selected subject.
2023-2027-ECE-B
Output Format:
• Display the output of the head() function applied to the Pandas DataFrame.
• Print the marks of the specified student that meet the specified criteria.
Source Code:
stdMarksDf.py
# Predefined dictionary with at least five keys, each representing a student's subject marks
std_marks = {
'A': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
'B': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'C': [11, 22, 33, 44, 55, 66, 77, 88, 99, 101],
'D': [103, 105, 109, 114, 125, 135, 149, 154, 162, 185],
'E': [52, 86, 75, 41, 32, 71, 68, 94, 73, 69]
}
df = pd.DataFrame(std_marks)
student = input()
threshold = float(input())
print(df.head())
filtered_marks = df[df[student] > threshold][student]
if filtered_marks.empty:
print("Invalid")
else:
print(filtered_marks)
Page No: 83
0 10 1 11 103 52
1 20 2 22 105 86
2 30 3 33 109 75
3 40 4 44 114 41
4 50 5 55 125 32
ID: 249X5A04L9
3 40
4 50
5 60
6 70
7 80
8 90
9 100
Name: A, dtype: int64
Test Case - 2
2023-2027-ECE-B
User Output
E
100
A B C D E
0 10 1 11 103 52
Test Case - 3
User Output
C
62.83
A B C D E
0 10 1 11 103 52
1 20 2 22 105 86
2 30 3 33 109 75
3 40 4 44 114 41
4 50 5 55 125 32
5 66
6 77
7 88
8 99
9 101
Name: C, dtype: int64
Exp. Name: Pandas - series creation and
S.No: 53 Date: 2024-11-07
manipulation
Aim:
Page No: 84
Write a Python program that takes a list of numbers from the user, creates a Pandas series from it, and then
calculates the mean of even and odd numbers separately using the groupby and mean() operations.
Input Format:
• The user should enter a list of numbers separated by space when prompted.
ID: 249X5A04L9
Output Format:
• The program should display the mean of even and odd numbers separately.
• Each mean value should be displayed with a label indicating whether it corresponds to even or odd
numbers.
Source Code:
seriesManipulation.py
import pandas as pd
2023-2027-ECE-B
# Take inputs from the user to create a list of numbers
numbers = list(map(int, input().split()))
print("Mean of even and odd numbers:")
se = pd.Series(numbers)
grouped = se.groupby(se.apply(lambda x: 'Odd' if x%2 == 1 else 'Even')).mean()
grouped = grouped.reindex(['Odd','Even'])
grouped = grouped.dropna()
User Output
1 2 3 4 5 6 7 8 9 10
Mean of even and odd numbers:
Odd 5.0
Even 6.0
dtype: float64
Test Case - 2
User Output
4 4 4 6 6 2 2 2 10 12 14 16
Mean of even and odd numbers:
Even 6.833333
dtype: float64
User Output
1 5 7 9 11 13 15 17 111 21 25
Mean of even and odd numbers:
Odd 21.363636
dtype: float64
Page No: 85
ID: 249X5A04L9
2023-2027-ECE-B
G Pulla Reddy Engineering College (Autonomous)
S.No: 54 Exp. Name: Shape, Size and Reshaping Date: 2024-10-29
Aim:
Write a Python program to perform the following tasks:
Page No: 86
• Create a NumPy array with values ranging from 1 to 12.
• Find and display the shape of the array.
• Find and display the size of the array.
• Reshape the array by prompting the user to enter the number of rows and columns.
• Display the reshaped array and its new shape, or display an error message as "Cannot reshape the array" if
ID: 249X5A04L9
it cannot be reshaped into the specified dimensions.
Input Format:
• No input is required for the creation of the initial array, as the values are predefined from 1 to 12.
• The user will be prompted to enter two integers:
• The first integer represents the new number of rows.The second integer represents the new number of
columns.
Output Format:
• The program should first display the original array.
• The program should display the shape and size of the original array.
• If the reshaping is successful, the program should display the reshaped array and its new shape.
• If the reshaping is not possible, the program should display an error message indicating the issue.
2023-2027-ECE-B
Source Code:
operations.py
import numpy as np
print(f"Shape: {shape}")
print(f"Size: {size}")
print(reshaped_array)
else:
print("Cannot reshape the array")
'issue'
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Page No: 87
[ 1 2 3 4 5 6 7 8 9 10 11 12]
Shape: (12,)
Size: 12
New rows:
2
ID: 249X5A04L9
New columns:
4
Cannot reshape the array
Test Case - 2
User Output
[ 1 2 3 4 5 6 7 8 9 10 11 12]
Shape: (12,)
Size: 12
2023-2027-ECE-B
New rows:
4
New columns:
3
[[ 1 2 3]
[ 4 5 6]
Test Case - 3
User Output
[ 1 2 3 4 5 6 7 8 9 10 11 12]
Shape: (12,)
Size: 12
New rows:
6
New columns:
2
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
S.No: 55 Exp. Name: Numpy array creation Date: 2024-11-07
Aim:
Write a Python program that takes two integer inputs, a start value, and an end value from the user. Use these
Page No: 88
inputs to create a NumPy array with values ranging from the start value to the end value inclusive. Display the
array.
Input Format:
• The first integer represents the start value.
ID: 249X5A04L9
• The second integer represents the end value.
Output Format:
• The program should output a message displaying the created NumPy array.
Source Code:
createArray.py
import numpy as np
2023-2027-ECE-B
end = int(input( ))
User Output
10
50
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50]
Test Case - 2
User Output
4
9
[4 5 6 7 8 9]