Python - Lab - Manual - B.Tech. - Sem-2 Aneek
Python - Lab - Manual - B.Tech. - Sem-2 Aneek
Python - Lab - Manual - B.Tech. - Sem-2 Aneek
LAB MANUAL
For
Submitted by:
Submitted to:
Manish Dahiya
Ms. Shabda
231302125
AIML Trainer
4. Code of Ethics 7
5. Course Syllabus 8
6. Course Outcome and COs-POs, COs-SOs mapping of the course 9
7. List of Experiments 10
● To impart higher education at par with global standards that meets the changing needs of the society
● To provide access to quality education and to improve quality of life, both at individual and community
levels with advancing knowledge in all fields through innovations and ethical research.
● To actively engage with and promote growth and welfare of the surrounding community through suitable
extension and outreach activities
● To develop socially responsible citizens, fostering ethical values and compassion through participation in
community engagement, extension and promotion activities.
● To create competitive and coordinated environment wherein the individual develop skills and a lifelong
learning attitude to excel in their endeavours.
● To develop Centers of Excellence culminating in achieving the cutting-edge technology in all fields.
PEO1: Graduates of the Computer Science and Engineering will contribute to the Nation’s growth through
their ability to solve diverse and complex computer science and engineering problems across a broad range
of application areas. (PEO1 is focused on Problem Solving)
PEO2: Graduates of the Computer Science and Engineering will be successful professionals, designing and
implementing Products & Services of global standards in the field of Computer Science & Engineering,
becoming entrepreneurs, Pursuing higher studies & research. (PEO 2 is focused on Professional Success)
PEO3: To install leadership qualities in graduates with a sense of confidence, professionalism and ethical
attitude to produce professional leaders for serving the society.
PEO3: Graduates of the Computer Science and Engineering Program will be able to adapt to changing
scenario of dynamic technology with an ability to solve larger societal problems using logical and flexible
approach in decision making. (PEO 3 is focused on Attaining Flexibility and Adaptability)
Program Outcomes (POs)
Engineering Graduates will be able to understand and apply the below mentioned PO’s.
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multi-disciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)
A Graduate of Computer Science and Engineering Program will be able to acquire the below mentioned
PSOs:
PSO1: Exhibit attitude for continuous learning and deliver efficient solutions for emerging challenges in the
computation domain.
PSO2: Apply standard software engineering principles to develop viable solutions for Information
Technology Enabled Services (ITES).
CAC
Analyze a complex computing problem and to apply principles of computing and
SO1
other relevant disciplines to identify solutions.
Design, implement and evaluate a computing-based solution to meet a given set of
SO2
computing
requirements in the context of the program ‘s discipline.
SO3 Communicate effectively in a variety of professional contexts.
Recognize professional responsibilities and make informed judgments in
SO4
computing practice
based on legal and ethical principles.
Function effectively as a member or leader of a team engaged in activities
SO5
appropriate to the
program ‘s discipline.
Identify and analyse user needs and to take them into account in the selection,
SO6 creation, integration, evaluation, and administration of computing-based systems
EAC
An ability to identify, formulate, and solve complex engineering problems by
SO1
applying principles of engineering, science, and mathematics.
An ability to apply engineering design to produce solutions that meet specified needs
SO2 with consideration of public health, safety, and welfare, as well as global, cultural,
social, environmental, and economic factor.
SO7 An ability to acquire and apply new knowledge as needed, using appropriate learning
strategies.
Code of Ethics
I. To uphold the highest standards of integrity, responsible behaviour, and ethical conduct in
professional activities.
1. to hold paramount the safety, health, and welfare of the public, to strive to comply with
ethical design and sustainable development practices, to protect the privacy of others, and
to disclose promptly factors that might endanger the public or the environment;
2. to improve the understanding by individuals and society of the capabilities and societal
implications of conventional and emerging technologies, including intelligent systems.
3. to avoid real or perceived conflicts of interest whenever possible, and to disclose them
to affected parties when they do exist;
4. to avoid unlawful conduct in professional activities, and to reject bribery in all its forms;
5. to seek, accept, and offer honest criticism of technical work, to acknowledge and correct
errors, to be honest and realistic in stating claims or estimates based on available data, and
to credit properly the contributions of others;
6. to maintain and improve our technical competence and to undertake technological tasks
for others only if qualified by training or experience, or after full disclosure of pertinent
limitations;
II. To treat all persons fairly and with respect, to not engage in harassment or discrimination, and
to avoid injuring others.
7. to treat all persons fairly and with respect, and to not engage in discrimination based on
characteristics such as race, religion, gender, disability, age, national origin, sexual
orientation, gender identity, or gender expression;
8. to not engage in harassment of any kind, including sexual harassment or bullying
behaviour;
9. to avoid injuring others, their property, reputation, or employment by false or malicious
actions, rumours or any other verbal or physical abuses;
III. To strive to ensure this code is upheld by colleagues and co-workers.
10. to support colleagues and co-workers in following this code of ethics, to strive to
ensure the code is upheld, and to not retaliate against individuals reporting a violation.
1. Name of the Department- Computer Science Engineering
2. Data Analysis L T P
Course using Python -
Name Lab
3. 0 0 4
Course
Code
8. Course Description
This course presents a gentle introduction into the concepts of data analysis, the role of a Data Analyst, and
the tools that are used to perform daily functions. You will gain an understanding of the data ecosystem and
the fundamentals of data analysis, such as data gathering or data mining. You will then learn the soft skills
that are required to effectively communicate your data to stakeholders, and how mastering these skills can
give you the option to become a data driven decision maker.
9. Learning objectives:
• Provide you with the knowledge and expertise to become a proficient data
scientist
• Demonstrate an understanding of statistics and machine learning concepts that are
vital for data science;
• Produce Python code to statistically analyse a dataset;
• Critically evaluate data visualisations based on their design and use for
Communicating stories from data.
1. Explain how data is collected, managed and stored for data science;
2. Understand the key concepts in data science, including their real-world applications and
the toolkit used by data scientists.
3. Implement data collection and management scripts using MongoDB.
1. Python Installation
2. Python Programming Basics
3. Python Data Structures
4. NumPy, Array & Vectorized Computation
5. Data Manipulation with Pandas.
6. Data Visualization in Python using Matplotlib and Seaborn
COs-POs mapping of the course
P P PO P P PO P P P P P PO1 PS PS
O O 3 O O 6 O O O O1 O1 2 O1 O2
CO 1 2 4 5 7 8 9 0 1
CO-1 - - - 3 - 3 - - - - - - - 3
CO-2 - - 3 - - 3 - 3 - - - - -
CO-3 3 3 - 3 - 3 - - - - - - 3 -
a) Explicitly indicate which of the student outcomes listed in Criterion 3 or any other
outcomes are addressed by the course.
Python Installation
Installing Anaconda on Windows
Experiment No. 1
• Download the Anaconda installer from the following link
https://www.anaconda.com/products/individual#windows
Spyder
Python Programming Basics
Experiment No. 2
Q. Add Two Numbers with “+” Operator:
Here num1 and num2 are variables and we are going to add both variables with the +
operator in Python.
# printing values
print("Sum of", num1, "and", num2 , "is", sum)
Output:
Sum of 15 and 12 is 27
Experiment No. 3
Q. Add Two Numbers with User Input:
In the below program to add two numbers in Python, the user is first asked to enter two
numbers, and the input is scanned using the Python input() function and stored in the
variables number1 and number2.
Then, the variable’s number1 and number2 are added using the arithmetic operator +,
and the result is stored in the variable sum.
Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Experiment No. 4
Q. Add Two Numbers Using operator.add() Method:
Initialize two variables num1, and num2. Find sum using the operator.add() by passing
num1, and num2 as arguments and assign to sum. Display num1, num2 and sum.
# Python3 program to add two numbers
num1 = 15
num2 = 12
# printing values
print("Sum of {0} and {1} is {2}" .format(num1,
num2, sum))
Output
Sum of 15 and 12 is 27
Experiment No. 5
Q. Add Two Numbers in Python Using Function
This program show adding two numbers in Python using function. We can define a
function that accepts two integers and returns their sum.
#To define a function that take two integers
# and return the sum of those two numbers
def add(a,b):
return a+b
Output
Sum of 10 and 5 is 15;
Experiment No. 6
Q. Write a program in Python to make a simple calculator.
Experiment No. 7
Q. Create a Python program to find sum of elements in list (using for loop)
total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
Output
Sum of all elements in given list: 74
Experiment No. 8
Q. Write a Python program to find sum of elements in list (using while loop)
total = 0
ele = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
Output
Sum of all elements in given list: 74
Experiment No. 9
Q. Write a Python Program to count the number of vowels in a string.
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
Output:
Case 1:
Enter string:Hello world
Number of vowels are:
3
Case 2:
Enter string:WELCOME
Number of vowels are:
3
Experiment No. 10
Q. Create a Python program and check how many dimensions the arrays
have
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Output:
0
1
2
3
Experiment No. 11
Q. Create an array with 5 dimensions using ndmin using a vector with values
1,2,3,4 and verify that last dimension has value 4
import numpy as np
print(arr)
print('shape of array :', arr.shape)
Output:
[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)
Experiment No. 12
Q. Convert the following 1-D array with 12 elements into a 2-D array.
newarr = arr.reshape(4, 3)
print(newarr)
Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Experiment No. 13
Q. Write Python code to demonstrate trigonometric function.
import numpy as np
# create an array of angles
angles = np.array([0, 30, 45, 60, 90, 180])
Output:
Sine of angles in the array:
[0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01
1.00000000e+00 1.22464680e-16]
Experiment No. 14
Q. Python code demonstrate statistical function.
import numpy as np
# construct a weight array
weight = np.array([50.7, 52.5, 50, 58, 55.63, 73.25, 49.5, 45])
# percentile
print('\n Weight below which 70 % student fall: ')
print(np.percentile(weight, 70))
# mean
print('\n Mean weight of the students: ')
print(np.mean(weight))
# median
print('\n Median weight of the students: ')
print(np.median(weight))
# standard deviation
print('\n Standard deviation of weight of the students: ')
print(np.std(weight))
# variance
print('\n Variance of weight of the students: ')
print(np.var(weight))
# average
print('\n Average weight of the students: ')
print(np.average(weight))
Output:
Minimum and maximum weight of the students:
45.0 73.25
Experiment No. 15
Q. (a) creating series from ndarray
data = np.array(['a','b','c','d'])
print(data)
s_arr = pd.Series(data)
print(s_arr)
Output:
['a' 'b' 'c' 'd']
0 a
1 b
2 c
3 d
dtype: object
Output:
a 0.0
bat 1.0
10 2.3
dtype: float64
Output:
bat 1.0
2 NaN
10 2.3
dtype: float64
Experiment No. 16
Q. Create a DataFrame in Python using Pandas:
import pandas as pd
data = {'state':['Ohio', 'Delhi', 'Ohio', 'Nevada','Nevada','Nevada'],
'year':[2000,2003 ,2001 ,2000, 2001, 2002],
'pop':[1.5, 1.6, 5,3.9, 4, 6.7]}
#data
frame = pd.DataFrame(data)
print(frame)
frame = pd.DataFrame(data,[10,11,12,13,14,15],['year','state','pop'])
frame
Output:
state year pop
0 Ohio 2000 1.5
1 Delhi 2003 1.6
2 Ohio 2001 5.0
3 Nevada 2000 3.9
4 Nevada 2001 4.0
5 Nevada 2002 6.7
1
2000 Ohio 1.5
0
1
2003 Delhi 1.6
1
1
2001 Ohio 5.0
2
1
2000 Nevada 3.9
3
1
2001 Nevada 4.0
4
year state pop
1
2002 Nevada 6.7
5
Experiment No. 17
import pandas as pd
# Create dataframe
info = pd.DataFrame({"P":[4, 7, 1, 8, 9],
"Q":[6, 8, 10, 15, 11],
"R":[17, 13, 12, 16, 14],
"S":[15, 19, 7, 21, 9]},
index =["Parker", "William", "Smith", "Terry", "Phill"])
# Print dataframe
info
Output:
Experiment No. 18
import pandas as pd
import numpy as np
N=5
df = pd.DataFrame({
'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),
'x': np.linspace(0,stop=N-1,num=N),
'y': np.random.rand(N),
'C': np.random.choice(['Low','Medium','High'],N).tolist(),
'D': np.random.normal(100, 10, size=(N)).tolist()
})
Df
Output:
Experiment No. 19
Matplotlib Inline
The output of plotting commands is displayed inline within frontends
like the Jupyter notebook, directly below the code cell that produced
it. The resulting plots will then also be stored in the notebook
document. %matplotlib inline should be the first command before
import command
#%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(10)
print(data)
plt.plot(data)
plt.show()
[0 1 2 3 4 5 6 7 8 9]
x = np.arange(0.0, 6.0, 0.01)
plt.plot(x, [x**2 for x in x]);
#plt.show()
Multiline Plot
plots are reset after each cell is evaluated, so for more complex plots
you must put all of the plotting commands in a single notebook cell
x = np.arange(0.0, 6.0, 0.01)
plt.plot(x, [x**2 for x in x])
plt.plot(x, [x**2.25 for x in x])
plt.plot(x, [x**2.5 for x in x]);
Experiment No. 20
Seaborn Session
import numpy as np
from matplotlib import pyplot as plt
def sinplot(flip=0.5):
x = np.linspace(0, 14, 100)
for i in range(1, 5):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
plt.show()
import seaborn as sns
sns.set_style("dark")
sinplot()
plt.show()
sns.set_style("white")
sinplot()
sns.despine()
plt.show()
Qualitative or categorical palettes are best suitable to plot the
categorical data.
current_palette = sns.color_palette()
sns.palplot(current_palette)
plt.show()
current_palette = sns.color_palette()
sns.palplot(sns.color_palette("Reds"))
plt.show()
By default, the values are centered from zero. You can control it with
parameter center by passing a value.
current_palette = sns.color_palette()
sns.palplot(sns.color_palette("BrBG", 7))
plt.show()