Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Record

The document outlines a series of practical Python programming exercises, including tasks such as implementing a Fibonacci series, separating even and odd numbers, checking for duplicate letters, performing arithmetic operations using lambda functions, filtering even numbers from a list, and creating classes to represent cars and shapes. Each exercise includes an aim, algorithm, program code, output examples, and evaluation criteria. The exercises are designed for students to demonstrate their understanding of Python programming concepts and practices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Record

The document outlines a series of practical Python programming exercises, including tasks such as implementing a Fibonacci series, separating even and odd numbers, checking for duplicate letters, performing arithmetic operations using lambda functions, filtering even numbers from a list, and creating classes to represent cars and shapes. Each exercise includes an aim, algorithm, program code, output examples, and evaluation criteria. The exercises are designed for students to demonstrate their understanding of Python programming concepts and practices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

INDEXCollege Vision and Mission

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 ..........................................................................

……………….Laboratory during the academic year ..........................

Staff in-charge Head of the Department

Submitted for the End Semester practical Examination held on............

Internal Examiner External Examiner


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 ..........................................................................

……………….Laboratory during the academic year ..........................

Staff in-charge Head of the Department

Submitted for the End Semester practical Examination held on............

Internal Examiner External Examiner


INDEX

PAGE
S.NO DATE TITLE MARK SIGN
NO

1 Build a python program to implement Fibonacci series.


27/2/2024 1

Build a python program to get a range of numbers from user


2 and to separate even numbers and odd numbers respectively.
5/3/2024 3
Build a function in Python to check duplicate letters. It must
accept a string, i.e., a sentence. The function should return
3 True if the sentence has any word with duplicate letters, else
5/3/2024 return False. 5

4 Build a program to perform arithmetic operations using


12/3/2024 lambda function. 7
Build a Python program that takes a list of numbers as input
5 and returns a new list containing only the even numbers from
12/3/2024 the input list. 9
Build a python program to create a class called Car with
6 attributes Company, model, and year. Implement a method
19/3/2024 that returns the age of the car in years. 11
Build a python program to create a base class called Shape
that has a method called area which returns the area of the
shape (set it to 0 for now). Then, create two derived classes
7 Rectangle and Circle that inherit from the Shape class to
25/3/2024 calculate the area of derived classes. 13

8 Build a python program to implement aggregation using


9/4/2024 Numpy. 16
9 Build a python program to perform Indexing and Sorting.
9/4/2024 18
10 Build a python program to perform Handling of missing data.
16/4/2024 20
11 Build a python program to perform usage of Pivot table using
16/4/2024 Titanic datasets 24
12
Build a python program to perform use of eval () and query ()
23/4/2024 26
13
Build a python program to perform Scatter Plot
30/4/2024 29
14 Build a python program to perform 3D plotting
30/4/2024 31
15 Customer Order Receipt Generation Program in Python
7/5/2024 33
EXP. NO. 1 Build a python program to implement Fibonacci series.
DATE: 27/2/2024
Aim
To write a python program to perform Fibonacci series.
Algorithm
1. Start the program
2. Create a function def fib(n)
3. Initialized the first term to 0 and the second term to 1.
4. Use for loop is used to iterate the values till the given number.
5. At last, it will print fibonacci series
6. Stop the program
Program
def fib(n):
a=0
b=1
if n == 1:
print(a)
else:
print(a)
print(b)
for i in range(2,n):
c=a+b
a=b
b=c
print(c)
fib(10)

1
Output :
0
1
1
2
3
5
8
13
21
34

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 5

Program and Output 15

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)

print(f"\nEven numbers in the range {start} to {end}: {even_numbers}")


print(f"Odd numbers in the range {start} to {end}: {odd_numbers}")
except ValueError:
print("Invalid input. Please enter valid integers.")

if name == " main ":


main()

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]

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 5

Program and Output 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.

Criteria Maximum Marks Marks Obtained


Aim and Algorithm 5
Program and Output 15
Viva 5
Total 25

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

# Filter even numbers


even_numbers_list = filter_even_numbers(numbers)

# Display the result


print("\nOriginal List:", numbers)
print("List of Even Numbers:", even_numbers_list)

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]

Criteria Maximum Marks Marks Obtained


Aim and Algorithm 5
Program and Output 15
Viva 5
Total 25

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

Criteria Maximum Marks Marks Obtained


Aim and Algorithm 5
Program and Output 15
Viva 5
Total 25

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

if name == " main ":


main()

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

Criteria Maximum Marks Marks Obtained


Aim and Algorithm 5
Program and Output 15
Viva 5
Total 25

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)

# Display the original DataFrame


print("Original DataFrame:")
print(df)

# Handling missing values


# 1. Drop rows with missing values
df_dropped = df.dropna()

# 2. Fill missing values with a specific value


df_filled = df.fillna(0)

# 3. Fill missing values with mean, median, or mode


df_filled_mean = df.fillna(df.mean()) # Replace with mean
df_filled_median = df.fillna(df.median()) # Replace with median
df_filled_mode = df.fillna(df.mode().iloc[0]) # Replace with mode

# Display the modified DataFrames


print("\nDataFrame after dropping rows with missing values:")
print(df_dropped)
print("\nDataFrame after filling missing values with 0:")
print(df_filled)
20
print("\nDataFrame after filling missing values with mean:")
print(df_filled_mean)
print("\nDataFrame after filling missing values with median:")
print(df_filled_median)
print("\nDataFrame after filling missing values with mode:")
print(df_filled_mode)

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

DataFrame after dropping rows with missing values:


Name Age Salary
0 Aravind 25.0 50000.0
1 Benjamin 30.0 60000.0
4 Eva 35.0 90000.0
6 Geetha 28.0 70000.0

DataFrame after filling missing values with 0:


Name Age Salary
0 Aravind 25.0 50000.0
1 Benjamin 30.0 60000.0
2 Charlie 0.0 75000.0
3 David 22.0 0.0
4 Eva 35.0 90000.0
5 Frank 0.0 80000.0
6 Geetha 28.0 70000.0

DataFrame after filling missing values with mean:


Name Age Salary
0 Aravind 25.0 50000.000000
1 Benjamin 30.0 60000.000000
2 Charlie 28.0 75000.000000
3 David 22.0 70833.333333
4 Eva 35.0 90000.000000
5 Frank 28.0 80000.000000
6 Geetha 28.0 70000.000000

DataFrame after filling missing values with median:


Name Age Salary
0 Aravind 25.0 50000.0
1 Benjamin 30.0 60000.0
2 Charlie 28.0 75000.0
3 David 22.0 72500.0
4 Eva 35.0 90000.0
5 Frank 28.0 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

Unnamed: 15 adult_male alone ... pclass sibsp survived


sex age ...
female 0.75 0.0 0.0 0.0 ... 6 4 2
1.00 0.0 0.0 0.0 ... 6 1 2
2.00 0.0 0.0 0.0 ... 15 9 2
3.00 0.0 0.0 0.0 ... 5 4 1
4.00 0.0 0.0 0.0 ... 13 4 5
5.00 0.0 0.0 1.0 ... 11 7 4
6.00 0.0 0.0 0.0 ... 5 4 1
7.00 0.0 0.0 0.0 ... 2 0 1
8.00 0.0 0.0 0.0 ... 5 3 1
9.00 0.0 0.0 0.0 ... 12 10 0
10.00 0.0 0.0 0.0 ... 3 0 0
... ... ... ... ... ... ... ...
male 42.00 0.0 10.0 6.0 ... 21 3 3
43.00 0.0 3.0 2.0 ... 8 1 0
44.00 0.0 6.0 3.0 ... 15 3 1
45.00 0.0 6.0 5.0 ... 10 1 2
45.50 0.0 2.0 2.0 ... 4 0 0
46.00 0.0 3.0 2.0 ... 4 1 0
47.00 0.0 7.0 7.0 ... 12 0 0
48.00 0.0 5.0 3.0 ... 8 2 3
[145 rows x 8 columns]

24
Output
Unnamed: 15 adult_male alone ... pclass sibsp survived

sex age ...


female 0.75 0.0 0 0 ... 6 4 2
1.00 0.0 0 0 ... 6 1 2
2.00 0.0 0 0 ... 15 9 2
3.00 0.0 0 0 ... 5 4 1
4.00 0.0 0 0 ... 13 4 5
... ... ... ... ... ... ... ...
male 70.00 0.0 2 1 ... 3 1 0
70.50 0.0 1 1 ... 3 0 0
71.00 0.0 2 2 ... 2 0 0
74.00 0.0 1 1 ... 3 0 0
80.00 0.0 1 1 ... 1 0 1

[145 rows x 8 columns]

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 5

Program and Output 15

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

Use of query() method


import pandas as pd
data = { "name": ["Sally", "Mary", "John"], "age": [50, 40, 30]}
df = pd.DataFrame(data)
print(df.query('age > 35'))

Output
name age
0 Sally 50
1 Mary 40

Criteria Maximum Marks Marks Obtained


Aim and Algorithm 5
Program and Output 15
Viva 5
Total 25

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

#Two lines to make our compiler able to draw:


plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

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.plot3D(x_line, y_line, z_line)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');

31
Output

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 5

Program and Output 15

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

5) Generate a random choice for the computer (1,2 or 3).

6) Compare the user’s choice and the computer’s choice according to the rules.

7) Announce whether the user or the computer won or if it was a draw.

8) Ask the user if they want to play again (Y/N).

9) Print the thank you message to the user.

33
Program:

import random module


import random
print('Winning rules of the game ROCK PAPER SCISSORS are :
'
+ "Rock vs Paper -> Paper wins
"
+ "Rock vs Scissors -> Rock wins
"
+ "Paper vs Scissors -> Scissor wins
")

while True:

print("Enter your choice


1 - Rock
2 - Paper
3 - Scissors
")

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

while choice > 3 or choice < 1:


choice = int(input('Enter a valid choice please ☺'))

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)

while comp_choice == choice:


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 (choice == 1 and comp_choice == 2):


print('paper wins =>', end="")
result = 'Paper'
elif (choice == 2 and comp_choice == 1):
print('paper wins =>', end="")
result = 'Paper'

if (choice == 1 and comp_choice == 3):


print('Rock wins =>
', end="")
result = 'Rock'
elif (choice == 3 and comp_choice == 1):
print('Rock wins =>
', end="")
result = 'RocK'

if (choice == 2 and comp_choice == 3):


print('Scissors wins =>', end="")
result = 'Scissors'
elif (choice == 3 and comp_choice == 2):
print('Scissors wins =>', end="")
result = 'Rock'

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

print("thanks for playing”)

35
36
Output:

Enter your choice

1 – Rock
2 – Paper
3- Scissors

Enter your choice:1

Rock

Now its Computers Turn..


Computers choice is

Paper

Rock Vs Paper

Paper wins =><= Computer Wins=>


Do you want to play again? (Y/N)

Criteria Maximum Marks Marks Obtained


Aim and Algorithm 5
Program and Output 15
Viva 5
Total 25

Result
Thus the python program to implement a Stone , Paper and Scissors game and verified successfully.

35

You might also like