LABORATORY RECORD NOTE BOOK
AMITY UNIVERSITY CHHATTISGARH
Amity University Chhattisgarh
Amity School of Engineering & Technology
Batch: 2020 –2024
Enrollment Number: _A80105220005___
This is to certify that this is a bonafide record of the work done by Mr. _Mridul Dayama____
bearing enrollment number _A80105220005__ of B. Tech Computer Science & Engineering
semester VI, from Amity School of Engineering & Technology, Amity University Chhattisgarh in the
Data Science using Python Lab Laboratory with Course Code DS3602.
University Examination held on ------------------------------------------.
Facultyin-charge Director-ASET
Examiner- 1
Examiner-2
INDEX
S.No Programs Date Sign
1 Demonstrate usage of branching and looping
statements.
2 Demonstrate Recursive functions.
3 Demonstrate Lists.
4 Demonstrate Tuples and Sets.
5 Demonstrate Dictionaries.
6 Demonstrate inheritance and exceptional
handling.
7 Demonstrate use of “re”
8 Demonstrate Aggregation.
9 Demonstrate Indexing and Sorting.
10 Demonstrate handling of missing data.
S.No Programs Date Sign
11 Demonstrate hierarchical indexing.
12 Demonstrate usage of Pivot table.
13 Demonstrate use of and query().
14 Demonstrate Scatter Plot.
15 Demonstrate 3D plotting.
Program 1: Write a program to demonstrate usage of branching and looping
statements.
Code:
# Branching
number = int(input("Enter a number: "))
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
Output:
Enter a number: 4
Number is positive
Code:
#looping
number = int(input("Enter a number: "))
print("Printing even numbers from 1 to", number)
i=1
while i <= number:
if i % 2 == 0:
print(i)
i += 1
Output:
Enter a number: 6
Printing even numbers from 1 to 6
246
Program 2: Write a program to demonstrate Demonstrate Recursive
functions.
Code:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Taking input from the user
limit = int(input("Enter the limit for the Fibonacci sequence: "))
# Printing the Fibonacci sequence
print("Fibonacci sequence up to", limit, ":")
for i in range(limit):
print(fibonacci(i), end=" ")
Output:
Enter the limit for the Fibonacci sequence: 10
Fibonacci sequence up to 10 :
0 1 1 2 3 5 8 13 21 34
Program 3: Write a program to demonstrate Lists.
Code:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Accessing elements of a list
print("List elements:")
for number in numbers:
print(number)
# Adding an element to the list
numbers.append(6)
print("List after adding an element:", numbers)
# Removing an element from the list
numbers.remove(3)
print("List after removing an element:", numbers)
# Getting the length of the list
length = len(numbers)
print("Length of the list:", length)
Output:
List elements:
1 2 3 4 5 List after adding an element: [1, 2, 3, 4, 5, 6]
List after removing an element: [1, 2, 4, 5, 6]
Length of the list: 5
Program 4: Write a program to demonstrate Tuples and Sets.
Code:
# Tuples
fruits = ("apple", "banana", "cherry", "durian")
# Accessing elements of a tuple
print("Tuple elements:")
for fruit in fruits:
print(fruit,end=" ")
Output:
Tuple elements:
apple banana cherry durian
Code:
# Sets
colors = {"red", "green", "blue", "red"}
# Adding an element to the set
colors.add("yellow")
print("Set after adding an element:", colors)
# Removing an element from the set
colors.remove("red")
print("Set after removing an element:", colors)
# Accessing elements of a set
print("Set elements:")
for color in colors:
print(color,end=" ")
Output:
Set after adding an element: {'red', 'yellow', 'blue', 'green'}
Set after removing an element: {'yellow', 'blue', 'green'}
Set elements:
yellow blue green
Program 5: Write a program to demonstrate Dictionaries.
Code:
student = {
"name": "John Doe",
"age": 20,
"grade": "A",
"subjects": ["Math", "Science", "History"]
}
# Accessing values in the dictionary
print("Student information:")
print("Name:", student["name"])
print("Age:", student["age"])
print("Grade:", student["grade"])
print("Subjects:", student["subjects"])
# Modifying values in the dictionary
student["age"] = 21
student["grade"] = "A+"
student["subjects"].append("English")
print("Updated student information:")
print("Name:", student["name"])
print("Age:", student["age"])
print("Grade:", student["grade"])
print("Subjects:", student["subjects"])
# Adding a new key-value pair to the dictionary
student["country"] = "USA"
print("Updated student information (with country):", student)
# Removing a key-value pair from the dictionary
del student["grade"]
print("Updated student information (without grade):", student)
# Checking if a key is present in the dictionary
if "name" in student:
print("Name is present in the dictionary")
else:
print("Name is not present in the dictionary")
# Getting the number of key-value pairs in the dictionary
num_pairs = len(student)
print("Number of key-value pairs in the dictionary:", num_pairs)
Output:
Student information:
Name: John Doe
Age: 20
Grade: A
Subjects: ['Math', 'Science', 'History']
Updated student information:
Name: John Doe
Age: 21
Grade: A+
Subjects: ['Math', 'Science', 'History', 'English']
Updated student information (with country): {'name': 'John Doe', 'age': 21, 'grade': 'A+', 'subjects': ['Math',
'Science', 'History', 'English'], 'country': 'USA'}
Updated student information (without grade): {'name': 'John Doe', 'age': 21, 'subjects': ['Math', 'Science',
'History', 'English'], 'country': 'USA'}
Name is present in the dictionary
Number of key-value pairs in the dictionary: 4
Program 6: Demonstrate inheritance and exceptional handling.
#Inheritance:-
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
output:-
#exceptional handling:-
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
Output:-
Program 7: Demonstrate use of “re”.
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
output:-
Program 8: Demonstrate Aggregation.
class Salary:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
def annual_salary(self):
return (self.pay*12)+self.bonus
class EmployeeOne:
def __init__(self, name, age, sal):
self.name = name
self.age = age
# initializing the sal parameter
self.agg_salary = sal # Aggregati
def total_sal(self):
return self.agg_salary.annual_salary()
salary = Salary(10000, 1500)
emp = EmployeeOne('Geek', 25, salary)
print(emp.total_sal())
Output:
Program 9: Demonstrate Indexing and Sorting.
#Indexing
fruits = [4, 55, 64, 32, 16, 32]
x = fruits.index(32)
print(x)
output:
#Sorting.
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
print(cars)
output:
Program 10: Demonstrate handling of missing data.
from sklearn.impute import SimpleImputer
imputer=SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(x[:,2:5])
x[:,2:5]=imputer.transform(x[:,2:5])
print(x)
output:
Program 11: Demonstrate hierarchical indexing.
#hierarchical indexing.
import pandas as pd
df = pd.read_csv('homelessness.csv')
col = df.columns
df_ind3 = df.set_index(['region', 'state', 'individuals'])
df_ind3_region = df_ind3.loc[['Pacific', 'Mountain']]
print(df_ind3_region.head(10))
output:
Program 12: Demonstrate usage of Pivot table
import pandas as pd
import numpy as np
df = pd.DataFrame({'First Name': ['Aryan', 'Rohan', 'Riya', 'Yash', 'Siddhant', ], 'Last Name': ['Singh', '
‘Agarwal', 'Shah', 'Bhatia', 'Khanna'], 'Type': ['Full-time Employee', 'Intern', 'Full-time Employee',
'Part-time Employee', 'Full-time Employee'], 'Department': ['Administration', 'Technical',
'Administration', 'Technical', 'Management'], 'YoE': [2, 3, 5, 7, 6], 'Salary': [20000, 5000, 10000,
10000, 20000]})
output = pd.pivot_table(data=df, index=['Type'], columns=['Department'], values='Salary',
‘aggfunc='mean')
output
output:
Program 13: Demonstrate use of and query().
import pandas as pd
data = pd.read_csv("employees.csv")
data.columns =
[column.replace(" ", "_") for column in data.columns]
data.query('Senior_Management == True',
inplace=True)
data
output:
Program 14: Demonstrate Scatter Plot.
# Scatter Plot
import numpy
import matplotlib.pyplot as plt
x = numpy.random.normal(5.0, 1.0, 1000)
y = numpy.random.normal(10.0, 2.0, 1000)
plt.scatter(x, y)
plt.show()
output:
Program 15: Demonstrate 3D plotting.
#3D plotting
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
# syntax for 3-D projection
ax = plt.axes(projection ='3d')
# defining all 3 axis
z = np.linspace(0, 1, 100)
x = z * np.sin(25 * z)
y = z * np.cos(25 * z)
# plotting
ax.plot3D(x, y, z, 'green')
ax.set_title('3D line plot geeks for geeks')
plt.show()
output: