Python
Python
Practical – 1
Aim: Study and Install the Anaconda python with Jupyter notebook and
Spyder.
Follow the steps below to install the Anaconda distribution of Python on Windows.
Steps:
1. Visit Anaconda.com/downloads
2. Select Windows
PIET/CE/2022 1
Enrollment no: 201340107002
At the Advanced Installation Options screen, recommend that you do not check "Add
Anaconda to my PATH environment variable"
PIET/CE/2022 2
Enrollment no: 201340107002
PIET/CE/2022 3
Enrollment no: 201340107002
● If you'd like run Spyder, just click on its Launch button. The IDE will open.
● You can write Python code directly on Console or in spyder editor. Run code using
F5.
Jupyter notebook
● One way to open a Jupyter notebook is to use the Windows Start Menu. Note that the
Anaconda distribution of Python must be installed to use the Windows Start Menu to open
a Jupyter notebook.
● Open the Windows start menu and select [Anaconda3(64 bit)] --> [Jupyter Notebook]
PIET/CE/2022 4
Enrollment no: 201340107002
● Try typing the code below in the first cell in the notebook to the right of the In [
]: prompt.
● Then click the run button in the middle of the menu at the top of the notebook or (Alt+
Enter) to run the code.
PIET/CE/2022 5
Enrollment no: 201340107002
PIET/CE/2022 6
Enrollment no: 201340107002
Practical – 2
Aim: Write a Python Program to Print Personal Details.
print("Enter Your Personan Details:")
name=input("Enter Your Name:")
dob=input("Enter Your DOB:")
email=input("Enter your mail Id:")
mobile=input("Enter Your Mobile Number:")
branch=input("Enter Your Branch:")
OUTPUT:
PIET/CE/2022 7
Enrollment no: 201340107002
Practical – 3
Aim: Write a Python Program to find a factorial of a number using function.
# Function Definition
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num1=input("Enter Number:")
num=int(num1)
print("Factorial of",num,"is",
factorial(num))
Output:
PIET/CE/2022 8
Enrollment no: 201340107002
Practical – 4
Aim: Write a Python Program to find a largest element in the array.
def largest(arr,n):
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr,n)
print ("Largest in given array is",Ans)
● Output:
PIET/CE/2022 9
Enrollment no: 201340107002
Practical – 5
Aim: Write a Python Program to Count even and Odd number in a list.
# creating an empty list
lst = []
print(lst)
#list1 = [10, 21, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
Output:
PIET/CE/2022 10
Enrollment no: 201340107002
Practical – 6
Aim: WAPP to accept elements in the form of a tuple and display their sum
and average.
tpl=eval(input('Enter elements of tuples:'))
print(tpl)
sum=0
n=0
for i in tpl:
sum=sum+i
n=n+1
avg=sum/n
print("Sum is:",sum)
print("average is:",avg)
● Output:
PIET/CE/2022 11
Enrollment no: 201340107002
Practical – 7
Aim: WAPP to create dictionary with cricket players name and score in a
match. Also retrieving runs by entering the player’s name.
d={}
n = int(input("How many element in Dictonary : "))
for i in range(n):
k = input("Enter Cricket Player Name : ")
print(k)
v = int(input("Enter Cricket Player Score: "))
print(v)
d.update({k: v})
print("Dictonary : ", d)
name = input("Enter Name : ")
runs = d.get(name, -1)
if runs == -1:
print('Not found')
else:
print('{} made runs {}'.format(name, runs))
● Output:
PIET/CE/2022 12
Enrollment no: 201340107002
Practical – 8
Aim: Understanding the tools: Jupyter Console, Jupyter Notebook.
Go to the Windows start menu and select [Anaconda Prompt] under [Anaconda3].
If you don't see the Anaconda Prompt in the Windows Start Menu, then you need to install the
Anaconda distribution of Python. The Anaconda Prompt window should look something like the
image below.
PIET/CE/2022 13
Enrollment no: 201340107002
This command starts the Jupyter notebook server. The output in the Anaconda Prompt will
look something like the output shown below:
Copy/paste this URL into your browser when you connect ...
http://localhost:8888/?token=6bdef677d3503fbb2 ...
A web browser should open, and you should be able to see the Jupyter file browser. If a web
browser doesn't open automatically, you can copy the web address from the Anaconda
Prompt and paste it into a web browser's address bar.
● One way to open a Jupyter notebook is to use the Windows Start Menu. Note that the
Anaconda distribution of Python must be installed to use the Windows Start Menu to open
a Jupyter notebook.
● Open the Windows start menu and select [Anaconda3(64 bit)] --> [Jupyter Notebook]
PIET/CE/2022 14
Enrollment no: 201340107002
● Try typing the code below in the first cell in the notebook to the right of the In [
]: prompt.
● Then click the run button in the middle of the menu at the top of the notebook or (Alt+
Enter) to run the code.
PIET/CE/2022 15
Enrollment no: 201340107002
PIET/CE/2022 16
Enrollment no: 201340107002
Practical – 9
Aim: Perform fundamental scientific computing using NumPy.
# To create an ndarray, we can pass a list, tuple or any array- like object into the array() method,
and it will be converted into an ndarray:
import numpy as np
arr=np.array([1,2,3]) #1-D
print("1-D",arr)
arr=np.array([[1,2,3],[4,5,6]])#2-D
print("2-D",arr)
#An array that has 2-D arrays (matrices) as its elements is called 3-D array.
arr=np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])#3-D
print("3-D",arr)
print("dimension=",arr.ndim) # NumPy Arrays provides the ndim attribute that returns an integer
that tells us how many dimensions the array have.
#NumPy arrays start with 0, meaning that the first element has index 0, and the second has index
1 etc.
arr=np.array([1,2,3])
print(arr[0])
#To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.
arr=np.array([[1,2,3],[4,5,6]])
print(arr[1,2])
PIET/CE/2022 17
Enrollment no: 201340107002
#From the second element, slice elements from index 1 to index 4 (not included):
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print("Sliced 2-D Array",arr[1, 1:4])
#data type
arr = np.array(['apple', 'banana', 'cherry'])
print("Data type",arr.dtype)
#Copy
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print("Original Array",arr)
print("Copied Array",x)
PIET/CE/2022 18
Enrollment no: 201340107002
#sorting
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
#Addition
arr1 = np.array([[1, 2, 3],[1,2,3],[1,2,3]])
arr2 = np.array([[4, 5, 6],[4,5,6],[4,5,6]])
arr3=arr1+arr2
print("Addition:",arr3)
arr4=arr1-arr2
print("Subtraction:",arr4)
arr5=arr1/arr2
print("Division:",arr5)
arr6=arr1.dot(arr2)
print("Mtarix Multiplication:",arr6)
arr7=np.matmul(arr1,arr2)
print("Mtarix Multiplication:",arr7)
arr8=arr1 @arr2
print("Mtarix Multiplication:",arr8)
OUTPUT:
PIET/CE/2022 19
Enrollment no: 201340107002
PIET/CE/2022 20
Enrollment no: 201340107002
Practical – 10
Aim: Perform data analysis using pandas.
#Pandas program to read a csv file from a specified source and print the first 5 rows
import pandas as pd
diamonds = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-
data/master/diamonds.csv')
print(diamonds)
#Write a Pandas program to read a csv file from a specified source and print the first 5 rows.
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 50)
diamonds = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-
data/master/diamonds.csv')
print("First 5 rows:")
print(diamonds.head())
#Pandas program to select a series from diamonds DataFrame. Print the content of the series.
diamonds = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-
data/master/diamonds.csv')
print(diamonds['carat'])
#Pandas program to find the number of rows and columns and data type of eac h column of
diamonds Dataframe.
import pandas as pd
diamonds = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-
data/master/diamonds.csv')
print("Number of rows and columns:")
print(diamonds.shape)
print("\nData type of each column:")
print(diamonds.dtypes)
PIET/CE/2022 21
Enrollment no: 201340107002
OUTPUT:
PIET/CE/2022 22
Enrollment no: 201340107002
Practical – 11
Aim: Implement machine learning using Scikit-learn
import pandas as pd
data = pd.read_csv("iris.csv")
print("Shape of the data:")
print(data.shape)
print("\nData Type:")
print(type(data))
print("\nFirst 3 rows:")
print(data.head(3))
#Python program using Scikit- learn to print the keys, number of rows-columns, feature names and
the description of the Iris data.
iris_data = pd.read_csv("iris.csv")
print("\nKeys of Iris dataset:")
print(iris_data.keys())
print("\nNumber of rows and columns of Iris dataset:")
print(iris_data.shape)
#Python program to get the number of observations, missing values and nan values.
iris = pd.read_csv("iris.csv")
print(iris.info())
PIET/CE/2022 23
Enrollment no: 201340107002
OUTPUT:
PIET/CE/2022 24
Enrollment no: 201340107002
Practical – 12
Aim: Plot the data using matplotlib.
#Python program to draw a line using given axis values with suitable label in the x axis , y axis
and a title.
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3]
# y axis values
y = [2,4,1]
# Plot lines and/or markers to the Axes.
plt.plot(x, y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Sample graph!')
# Display a figure.
plt.show()
OUTPUT:
PIET/CE/2022 25
Enrollment no: 201340107002
Practical – 13
Aim: Parse HTML documents using Beautiful Soup.
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>An example of HTML page</title>
</head>
<body>
<h2>This is an example HTML page</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.</p>
<p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from
w3resource.com</a></p>
<p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from
w3resource.com</a></p>
</body>
</html>
"""
PIET/CE/2022 26
Enrollment no: 201340107002
PIET/CE/2022 27