Python Record
Python Record
Register Number :
Name :
Subject Name/Subject Code :
Branch :
Year/Semester :
Certificate
Certified that this is the bonafide record of Practical work done by
the above student in the ..........................................................................
Branch :
Year/Semester :
Certificate
Certified that this is the bonafide record of Practical work done by
the above student in the ..........................................................................
PAGE
S.NO DATE TITLE MARK SIGN
NO
1
Output :
0
1
1
2
3
5
8
13
21
34
Viva 5
Total 25
Result:
Thus the python program to perform Fibonacci series has been executed and output is verified
successfully.
2
EXP. NO. 2 Build a Python program to get a range of numbers from user and to separate
even numbers and odd numbers respectively
DATE: 05/03/2024
Aim
To write a Python program to get a range of numbers from user and to separate even numbers and odd
numbers respectively.
Algorithm
1. Start the program
2. Create a function def separate_even_odd_numbers(start, end)
3. Create an empty list for even_numbers and odd_numbers.
4. Use for loop is used to iterate the values till the given number.
5. Check the condition if num %2==0. If True print even numbers in the new list else print the odd
numbers in the new list.
6. At last, it will print the odd and even numbers list
7. Stop the program
Program
def separate_even_odd_numbers(start, end):
even_numbers = []
odd_numbers = []
for num in range(start, end + 1):
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
return even_numbers, odd_numbers
def main():
try:
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
if start > end:
print("Invalid range. Please ensure the start is less than or equal to the end.")
return
even_numbers, odd_numbers = separate_even_odd_numbers(start, end)
3
Output
Enter the start of the range: 0
Enter the end of the range: 15
Even numbers in the range 0 to 15: [0, 2, 4, 6, 8, 10, 12, 14]
Odd numbers in the range 0 to 15: [1, 3, 5, 7, 9, 11, 13, 15]
Viva 5
Total 25
Result
Thus the python program to perform separation of odd and even numbers from the user input has
been executed and output is verified successfully.
4
EXP. NO. 3
Build a python program to check duplicate letters
DATE: 5/3/2024
Aim
To create a function in python to check duplicate letters. It must accept a string,i.e., a sentence. The
function should return True if the sentence has any word with duplicate letters, else return False.
Algorithm
1. Start the program
2. Create a function def has_duplicate_letters(sentence)
3. Use the split () function to separate the letters in a given sentence.
4. Use for loop to print the each and every char in a given string.
5. Use if condition to check the duplicate char in the given character set. If True Found duplicate letters
in the current word.
6. Stop the program
Program
def has_duplicate_letters(sentence):
words = sentence.split()
for word in words:
char_set = set()
for char in word:
if char in char_set:
return True # Found duplicate letters in the current word
char_set.add(char)
return False # No duplicate letters found in any word
# Example usage:
sentence_input = input("Enter a sentence: ")
result = has_duplicate_letters(sentence_input)
if result:
print("The sentence has words with duplicate letters.")
else:
print("No words in the sentence have duplicate letters.")
5
Output 1 :
Enter a sentence: This is my first program.
The sentence has words with duplicate letters.
Output 2 :
Enter a sentence: The quick brown fox jumps over the lazy dog.
No words in the sentence have duplicate letters.
Result
Thus the python program to check duplicate letters in the given string has been executed and output is
verified successfully.
6
EXP. NO. 4 Build a python program to perform arithmetic operations using lambda
function
DATE: 12/3/2024
Aim
To write a python program to perform arithmetic operations using lambda function.
Algorithm
1. Start the program
2. Read two inputs num1 and num2
3. Use the lambda function to perform arithmetic operations such as add, subtract, multiply and divide.
4. Call each lambda function by passing input arguments
5. Print the output values
6. Stop the program
Program
# Lambda functions for arithmetic operations
add = lambda x, y: x + y
subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y if y != 0 else "Cannot divide by zero"
# User input for operands
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform arithmetic operations
print(f"\nAddition: {add(num1, num2)}")
print(f"Subtraction: {subtract(num1, num2)}")
print(f"Multiplication: {multiply(num1, num2)}")
print(f"Division: {divide(num1, num2)}")
7
Output
Enter the first number: 12
Enter the second number: 6
Addition: 18.0
Subtraction: 6.0
Multiplication: 72.0
Division: 2.0
Maximum Marks
Criteria
Marks Obtained
Aim and Algorithm 5
Program and
15
Output
Viva 5
Total 25
Result
Thus the python program to perform arithmetic operations using lambda function has been executed
and output is verified successfully.
8
EXP. NO. 5 Build a python program that takes the list of numbers as input and returns the new
list containing only the even numbers from the input list
DATE: 12/3/2024
Aim
To create a python program that takes the list of numbers as input and returns the new list containing
only the even numbers from the input list.
Algorithm
1. Start the program
2. Create a function def filter_even_numbers(numbers)
3. Read two list, one is for read the input values and another is for store the output values
4. Use the lambda function to filter the even numbers in the input list
5. Print the output values in the separate list called even_numbers_list.
6. Stop the program
Program
# Function to filter even numbers from the input list
def filter_even_numbers(numbers):
even_numbers = filter(lambda x: x % 2 == 0, numbers)
return list(even_numbers)
# User input for a list of numbers
try:
input_numbers = input("Enter a list of numbers separated by spaces: ")
numbers = [int(x) for x in input_numbers.split()]
except ValueError:
print("Invalid input. Please enter valid numbers separated by spaces.")
9
Output
Enter a list of numbers separated by spaces: 5 64 3 8 36 21 80
Original List: [5, 64, 3, 8, 36, 21, 80]
List of Even Numbers: [64, 8, 36, 80]
Result
Thus the python program that takes the list of numbers as input and returns the new list containing only
the even numbers from the input list has been executed and output is verified successfully.
10
EXP. NO. 6 Build a python program to create a class called Car with attributes Company, model,
and year. Implement a method that returns the age of the car in years.
DATE:19/3/2024
Aim
To write a python program to create a class called Car with attributes Company, model, and year and
implement a method that returns the age of the car in years.
Algorithm
1. Start the program
2. Import datetime library function for calculate the age of car in years.
3. Create a class called car that contains attributes and methods
4. Create a function def init (self, company, model, year) that define the attributes
5. Create a function def calculate_age(self) that define the method to calculate the age of car
6. Read the objects for the super class to access base class attributes and methods.
7. Print the output values
8. Stop the program
Program
from datetime import datetime
class Car:
def init (self, company, model, year):
self.company = company
self.model = model
self.year = year
def calculate_age(self):
current_year = datetime.now().year
age = current_year - self.year
return age
# Example usage:
car1 = Car("Toyota", "Camry", 2019)
car2 = Car("Honda", "Civic", 2015)
print(f"Car 1: {car1.company} {car1.model}, Year: {car1.year}, Age: {car1.calculate_age()} years")
print(f"Car 2: {car2.company} {car2.model}, Year: {car2.year}, Age: {car2.calculate_age()} years")
11
Output
Car 1: Toyota Camry, Year: 2019, Age: 5 years
Car 2: Honda Civic, Year: 2015, Age: 9 years
Result
Thus, the python program to create a class called Car with attributes Company, model, and year and
implement a method that returns the age of the car in years has been executed and output is verified
successfully.
12
Build a python program to create a base class called Shape that has a method area which
EXP. NO. 7 returns the area of the shape (set it to 0 for now). Then, create two derived classes Rectangle
and circle that inherit from the Shape class to calculate the area of derived classes.
DATE:25/3/2024
Aim
To write a python program to create a base class called Shape that has a method area which returns the
area of the shape (set it to 0 for now). Then, create two derived classes Rectangle and circle that inherit from
the Shape class to calculate the area of derived classes.
Algorithm
1. Start the program
2. Import math library function to calculate area of rectangle and circle.
3. Create a base class called shape that contains a method area which returns default implementation
4. Create a derived class1 called rectangle which is derived from shape that contains attributes and
method to calculate area of rectangle.
5. Create a derived class2 called circle which is derived from shape that contains attributes and method
to calculate area of circle.
6. Read the objects for rectangle and circle to calculate the area
7. Print the output values
8. Stop the program
Program
import math
class Shape:
def area(self):
return 0 # Default implementation, to be overridden by subclasses
class Rectangle(Shape):
def init (self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle(Shape):
def init (self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius**2
def main():
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
rectangle = Rectangle(length, width)
radius = float(input("\nEnter the radius of the circle: "))
circle = Circle(radius)
print("\nCalculating areas:")
13
print(f"Area of Rectangle: {rectangle.area()}")
print(f"Area of Circle: {circle.area()}")
except ValueError:
print("Invalid input. Please enter valid numeric values.")
14
Output
Enter the length of the rectangle: 10
Enter the width of the rectangle: 5
Enter the radius of the circle: 7
Calculating areas:
Area of Rectangle: 50.0
Area of Circle: 153.93804002589985
Result
Thus, the python program to implement the multiple inheritance concept has been executed and output
is verified successfully.
15
EXP. NO. 8 Build a python program to implement aggregation using Numpy
DATE:9/4/2024
Aim
To write a python program to implement aggregation using Numpy.
Algorithm
1. Start the program
2. install NumPy Packages to python.
!pip install numpy
3. import numpy to python import numpy as np
4. Create single and multiple dimention Numpy arrays syntax: arr_name = np.array( [values] )
5. AGGREGATE FUNCTIONS: Python has several methods are available to perform
aggregations on data. It is done using the numpy and pandas libraries. The data must be
available or converted to a dataframe to apply the aggregation functions.
6. Use and implement aggregate functions like sum, min, max, mean, average, product, median,
standard deviation, variance.
7. Stop the program
Program
import numpy as np
def get_user_array():
try:
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
print("Enter the elements of the array row-wise (separated by space):")
elements = [list(map(int, input().split())) for _ in range(rows)]
return np.array(elements)
except ValueError:
print("Invalid input. Please enter valid numeric values.")
return None
def perform_aggregation(array):
if array is not None:
sum_result = np.sum(array)
mean_result = np.mean(array)
max_result = np.max(array)
min_result = np.min(array)
print("\nOriginal array:")
print(array)
print("\nAggregation results:")
print(f"Sum: {sum_result}")
print(f"Mean: {mean_result}")
print(f"Max: {max_result}")
print(f"Min: {min_result}")
def main():
user_array = get_user_array()
perform_aggregation(user_array)
if name == " main ":
main()
16
Output
Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of the array row-wise (separated by space):
25
68
Original array:
[[2 5]
[6 8]]
Aggregation results:
Sum: 21
Mean: 5.25
Max: 8
Min: 2
Maximum Marks
Criteria
Marks Obtained
Aim and Algorithm 5
Program and
15
Output
Viva 5
Total 25
Result
Thus the python program to implement aggregation functions using NumPy has been executed and
output verified successfully.
17
EXP. NO. 9
Build a python program to perform indexing and sorting
DATE: 9/4/2024
Aim
To write a python program to perform indexing and sorting.
Algorithm
1. Start the Program
2. Install numpy package to Python using !pip install numpy
3. import numpy to python using import numpy as np .
4. Create a single, two or multi-dimensional NumPy array .
5. To perform sorting, the syntax is np.sort(array).
6. Sort array by columns, rows.
7. Sort array by reversing order, reverse by indexing.
8. Lexsort function is implemented. np.lexsort((arr1,arr2))
9. Stop the program
Program
import numpy as np
def get_user_array():
try:
elements = list(map(int, input("Enter elements of the array separated by space: ").split()))
return np.array(elements)
except ValueError:
print ("Invalid input. Please enter valid numeric values.")
return None
def perform_indexing(array, index):
if array is not None:
try:
element_at_index = array[index]
print(f"\nElement at index {index}: {element_at_index}")
except IndexError:
print(f"Index {index} is out of bounds for the given array.")
def perform_sorting(array):
if array is not None:
sorted_array = np.sort(array)
print("\nOriginal array:")
print(array)
print("\nSorted array:")
print(sorted_array)
def main():
user_array = get_user_array()
if user_array is not None:
index = int(input("Enter the index for indexing: "))
perform_indexing(user_array, index)
perform_sorting(user_array)
if name == " main ":
main()
18
Output
Enter elements of the array separated by space: 2 4 6 7 3 1
Enter the index for indexing: 3
Element at index 3: 7
Original array:
[2 4 6 7 3 1]
Sorted array:
[1 2 3 4 6 7]
Maximum Marks
Criteria
Marks Obtained
Aim and Algorithm 5
Program and
15
Output
Viva 5
Total 25
Result
Thus, the python program to perform indexing and sorting using NumPy has been executed and out
verified successfully.
19
EXP. NO. 10
Build a python program to perform handling of missing data
DATE: 16/4/2024
Aim
To write a python program to perform handling of missing data using pandas object.
Algorithm
1. Start the program.
2. Import Pandas Package in the notebook: Command: import pandas.
3. Functions below are used to handle the missing data.
4. isnull(),notnull() - The function is used to identify if datasets has missing value or not. They return
boolean values.
5. dropna() - This function removes the row having missing value(s).
6. fillna() - This function fills the missing value with the provided value.
7. replace() - This function replaces the NaN with the provided word
8. interpolate() - This function fills the missing data with some value(s) generated after applying the
algorithm. It is better to use interpolate instead of hard coding.
9. Create Dataframe and Series and Handle the missing data using Pandas.
10. End the program.
Program
import pandas as pd
# Sample data with missing values
data = {
'Name': ['Aravind', 'Benjamin', 'Charlie', 'David', 'Eva', 'Frank', 'Geetha'],
'Age': [25, 30, None, 22, 35, None, 28],
'Salary': [50000, 60000, 75000, None, 90000, 80000, 70000]}
df = pd.DataFrame(data)
21
Output
Original DataFrame:
Name Age Salary
0 Aravind 25.0 50000.0
1 Benjamin 30.0 60000.0
2 Charlie NaN 75000.0
3 David 22.0 NaN
4 Eva 35.0 90000.0
5 Frank NaN 80000.0
6 Geetha 28.0 70000.0
22
DataFrame after filling missing values with mode:
Name Age Salary
0 Aravind 25.0 50000.0
1 Benjamin 30.0 60000.0
2 Charlie 22.0 75000.0
3 David 22.0 50000.0
4 Eva 35.0 90000.0
5 Frank 22.0 80000.0
6 Geetha 28.0 70000.0
Maximum Marks
Criteria
Marks Obtained
Aim and Algorithm 5
Program and
15
Output
Viva 5
Total 25
Result
Thus, the python program to perform handling of missing data using pandas has been executed and
output is verified successfully.
23
EXP. NO. 11 Build a python program to perform usage of Pivot table using Titanic datasets
DATE:16/4/2024
Aim
To write a python program to perform usage of Pivot table using Titanic datasets.
Algorithm
1. Start the Program.
2. Import pandas Package in the notebook Command: import pandas.
3. Import numpy Package in the notebook Command: import numpy.
4. Import dataset and implement the functions such as pandas.pivot_table
5. Using pivot_table function group the data accordingly.
6. Also use aggregate function in pivot_table function.
7. End the program.
Program
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = pd.pivot_table(df, index = ["sex","age"], aggfunc=np.sum)
print(result)
Pivot Titanic.csv
24
Output
Unnamed: 15 adult_male alone ... pclass sibsp survived
Viva 5
Total 25
Result
Thus the python program to perform usage of Pivot table using Titanic datasets has been executed and
output is verified successfully.
25
EXP. NO. 12 Build a python program to perform use of eval () and query ()
DATE: 23/4/2024
Aim
To write a python program to perform use of eval () and query () method using numpy and pandas
library.
Algorithm
1. Start the program
2. install and import pandas Packages to python.
!pip install pandas
3. import pandas as pd
4. install and import numpy Packages to python.
!pip install numpy
5. import numpy as np
6. Create DataFrames of random values
rng = np.random.RandomState(42)
df1, df2, df3, df4 = (pd.DataFrame(rng.rand(nrows, ncols))
for i in range(4))
7. EVAL(): The eval() function is used to evaluate an expression in the context of the calling dataframe
instance. The expression is evaluated over the columns of the dataframe.
8. QUERY(): The query() function is used to query the columns of a DataFrame with a boolean
expression.
9. Stop the program.
Program
Use of eval() method
# Perimeter of Square
def calculatePerimeter(l):
return 4*l
# Area of Square
def calculateArea(l):
return l*l
expression = input("Type a function: ")
for l in range(1, 5):
if (expression == 'calculatePerimeter(l)'):
print("If length is ", l, ", Perimeter = ", eval(expression))
elif (expression == 'calculateArea(l)'):
print("If length is ", l, ", Area = ", eval(expression))
26
else:
print('Wrong Function')
break
27
Output
Type a function: calculatePerimeter(l)
If length is 1 , Perimeter = 4
If length is 2 , Perimeter = 8
If length is 3 , Perimeter = 12
If length is 4 , Perimeter = 16
Output
name age
0 Sally 50
1 Mary 40
Result
Thus the python program to perform the uses of eval() and query() method has been executed and
output is verified successfully.
28
EXP. NO. 13 Build a python program to perform Scatter Plot
DATE: 30/4/2024
Aim
To write a python program to perform Scatter Plot using matplotlib.
Algorithm
1. Start the program
2. Import matplot library package using matplotlib.pyplot as plt
3. Import numpy library package using numpy as np
4. We can plot in graph using plt.plot(x,y)
5. We can label the x and y axis using plt.xlabel() .
6. We can also limit the x and y axis values to such limits using plt.xlim(0,1.8)
7. Some of the properties we used here are: legend,colors,markersize,linewidth
8. For scatter plot, we use plt.scatter(x,y) as syntax
9. Use plt.colorbar() to show color scale
10. End the program
Program
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'brown')
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color = '#000000')
plt.show()
29
Output
Maximum Marks
Criteria
Marks Obtained
Aim and Algorithm 5
Program and
15
Output
Viva 5
Total 25
Result
Thus, the python program to perform scatter plot using matplotlib has been executed and verified
successfully.
30
EXP. NO. 14 Build a python program to perform 3D plotting
DATE: 30/4/2024
Aim
To write a python program to perform 3D plotting using matplotlib.
Algorithm
1. Start the program.
2. Import matplotlib package and the submodule mplot3d toolkit in the notebook
3. Create a three-dimensional axes by passing the keyword projection='3d' to any of the
normal axes creation routines
4. Create a 3d plot usingthe ax.plot3D , ax.scatter3D , ax.countor and ax.contour3D functions.
5. Create a wireframe and a surface plotusing ax.plot_wireframe and ax.plot_surface functions
6. End the program.
Program
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams['figure.figsize']= (8,6)
ax = plt.axes(projection='3d')
omega =2
z_line = np.linspace(0,10,100)
x_line = np.cos(omega*z_line)
y_line = np.sin(omega*z_line)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
31
Output
Viva 5
Total 25
Result
Thus the python program to perform 3D plotting using matplotlib has been executed and verified
successfully.
32
EXP. NO. 15
Stone ,Paper ,Scissor Game Program in Python
DATE: 7/5/2024
Aim
To implement Stone ,Paper ,Scissor Game Program in Python.
Algorithm
1) Enter a loop to allow the game to be played multiple times.
2) Prompt the user to enter their choice (rock,Paper,scissor) by entering a corresponding number (1,2,3).
3) Validate the user input to ensure it is within the valid range (1 to 3). If not prompt again.
4) Convert the user’s numeric choice to its corresponding name (Rock, Paper, Scissors).
6) Compare the user’s choice and the computer’s choice according to the rules.
33
Program:
while True:
if choice == 1:
choice_name = 'Rock'
elif choice == 2:
choice_name = 'Paper'
else:
choice_name = 'Scissors'
print('User choice is
', choice_name)
print('Now its Computers Turn..')
comp_choice = random.randint(1, 3)
if comp_choice == 1:
comp_choice_name = 'RocK'
elif comp_choice == 2:
comp_choice_name = 'Paper'
else:
comp_choice_name = 'Scissors'
print("Computer choice is
34
", comp_choice_name)
print(choice_name, 'Vs', comp_choice_name)
if choice == comp_choice:
print('Its a Draw', end="")
result = "DRAW"
if result == 'DRAW':
print("<== Its a tie ==>")
if result == choice_name:
print("<== User wins ==>")
else:
print("<== Computer wins ==>")
print("Do you want to play again? (Y/N)")
ans = input().lower()
if ans == 'n':
break
35
36
Output:
1 – Rock
2 – Paper
3- Scissors
Rock
Paper
Rock Vs Paper
Result
Thus the python program to implement a Stone , Paper and Scissors game and verified successfully.
35