R.
RADHA KRISHNA N2000157
LAB-01
Basics, Loops, Functions, Classes and Objects of Python
1 .Write a program on Basics of Python.
print("My name is Radha Krishna")
a=True
print(type(a))
word="This is RK"
print(len(word))
print(word[:4])
print(word[5:7])
Output:
2. Write a Python Program on Data Types And Type Conversions
i=5
f=8.88
b=False
c=7j
#Printing datatypes of given input
print(type(i))
print(type(f))
print(type(c))
#type conversions
print(float(i))
print(complex(i))
print(int(f))
print(bool(f))
print(float(b))
print(hex(i))
print(bin(i))
print(oct(i))
Output:
Data Science With Python Laboratory 1
R. RADHA KRISHNA N2000157
[Link] a Python Program on Conditional Statements
#if
a=15
if a>10:
print("Value of a is greater than 10")
#if else
if (a<10):
print("Value of a is less than 10")
else:
print("Value of a is greater than 10")
#elif
ef=-6
if ef>0:
print("Positive +ve")
elif ef<0:
print("Negative -ve")
else:
print("Zero")
#nested
c=18
if (c>10):
if (c>20):
print("The c is greater than 20")
else:
print("THE c is less than 20 and greater than 10")
Output:
4 .Write a Python Program on Loops
#while
rk=3
while rk>0:
print(rk)
rk=rk-1
#for
for i in range(3):
print(i)
Output:
Data Science With Python Laboratory 2
R. RADHA KRISHNA N2000157
5 .Write a Python Program on Nested Loops
print("Multiplication Table:")
for row in range(1, 4): # Rows from 1 to 3
for col in range(1, 4): # Columns from 1 to 3
print(f"{row} x {col} = {row * col}", end=" ")
print()
print('\n')
Output:
6 .Write a Python Program on Output Formatting
a=input("Enter string ")
b=input("Enter string ")
c=input("Enter name ")
print("{} is in nuzvid".format(a))
print("The value in b is %s" %(b))
print("My name is",c)
Output:
7 .Write a Python Program on Lists And Tuples
#lists
n_l=[1,2,3,[4,8,10,19]]
print(n_l)
li=[1,2,3]
print(li)
[Link](4)
print(li)
m=[5,6,7]
[Link](m)
print(li)
print(5 in li)
print(90 not in li)
[Link](3)
print(li)
po=[Link]()
print(li)
print(po)
Data Science With Python Laboratory 3
R. RADHA KRISHNA N2000157
del li[0]
print(li)
[Link]()
print(li)
#Tuples
t1=(1,2,3)
t2=(4,5,6)
print(t1+t2)
print(t1)
Output:
8. Write a Python Program on Dictionary
d={1:'jalsa', 2:'kushi' , 3:'thammudu'}
print([Link](2))
print([Link](5))
d2={4:'gabbarsingh',5:'og'}
[Link](d2)
print(d)
print([Link]())
print([Link]())
print([Link]())
Output:
9 .Write a Python Program on Control Statements
#break
for i in range(1,10):
if i==5:
break
print(i)
#contine
Data Science With Python Laboratory 4
R. RADHA KRISHNA N2000157
for i in range(1,6):
if i==3:
continue
print(i)
#pass
for i in range(4):
if i==3:
pass
print(i)
Output:
[Link] a Python Program on Arithmetic Operators
a=int(input("Enter num1 "))
b=int(input("Enter num2 "))
print("Addition ",a+b)
print("Subtraction ",a-b)
print("Multiplication ",a*b)
print("Division ",a/b)
print("Modulus ",a%b)
print("Exponentiation ",a**b)
print("Floor division ",a//b)
Output:
11. Write a Python Program on Comparison operators
a=int(input("Enter num1 "))
b=int(input("Enter num2 "))
print(a>b)
print(a<b)
print(a>=b)
print(a<=b)
Data Science With Python Laboratory 5
R. RADHA KRISHNA N2000157
print(a==b)
print(a!=b)
Output:
12 .Write a Python Program on Assignment operators
a=int(input("Enter num1 "))
b=int(input("Enter num2 "))
a+=b
print(a)
a-=b
print(a)
a*=b
print(a)
a/=b
print(a)
a%=b
print(a)
a**=b
print(a)
a//=b
print(a)
Output:
13. Write a Python Program on Bitwise operators
a=int(input("Enter num1 "))
b=int(input("Enter num2 "))
print(a&b)
print(a|b)
print(~a)
Data Science With Python Laboratory 6
R. RADHA KRISHNA N2000157
print(a^b)
print(a>>2)
print(b<<3)
Output:
14 . Write a Python Program on logical operators
a=int(input("Enter num1 "))
b=int(input("Enter num2 "))
if (a>10 and b>10):
print("Both values are greater than 10")
else:
print("Both values are not greater than than 10")
if (a>10 or b>10):
print("One value is greater than 10")
else:
print("Both values are less than 10")
if (not(a==b)):
print("Both are not equal")
else:
print("Both are same")
Output:
15. Write a Python Program on Membership operators
s="RK "
print('z' in s)
print('k' not in s)
Output:
16. Write a Python Program on Identity operators
a=int(input("Enter num1 "))
b=int(input("Enter num2 "))
Data Science With Python Laboratory 7
R. RADHA KRISHNA N2000157
print(a is b)
print(a is not b)
Output:
17. Write a Python Program on Input split method
a,b=input("Enter 2 values with space ").split()
c,d=input("Enter 2 values with comma ").split(',')
print(a)
print(b)
print(c)
print(d)
Output:
18. Write a Python Program on Set operations
s={1,2,3,4}
print(s)
l=set(['a','b','c',1,2,3,4])
print(l)
[Link](78)
print(s)
[Link]((4,5))
print(s)
[Link](3)
print(s)
print([Link](l))
print(s&l)
print(l-s)
print(l^s)
Data Science With Python Laboratory 8
R. RADHA KRISHNA N2000157
Output:
19. Write a Python Program on Functions
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(f"Sum: {result}")
Output:
20. Write a Python Program on Recursion sum of digits
def sum_of_digits(n):
if n < 10:
return n
else:
return n % 10 + sum_of_digits(n // 10)
number = 1234
result = sum_of_digits(number)
print(f"Sum of the digits of {number}: {result}")
Output:
21. Write a Python Program on modules
from math import *
num=int(input("Enter number "))
print(radians(num))
print(tan(num))
print(fabs(num)
Output:
Data Science With Python Laboratory 9
R. RADHA KRISHNA N2000157
22. Write a Python Program on Classes and Objects
class Movie:
name = ''
rating = ''
def show_details(self):
print("Movie name:", [Link])
print("Rating:", [Link])
movie = Movie()
[Link] = "Gabbar Singh"
[Link] = "8/10"
movie.show_details()
Output:
[Link] a Python Program on Constructors
class Movie:
def __init__(self, name, rating):
[Link] = name
[Link] = rating
def show_details(self):
print("Movie name:", [Link])
print("Rating:", [Link])
movie = Movie("Attarintiki Daredi", "9/10")
movie.show_details()
Output:
24 .Write a Python Program on Inheritance
class Movie:
def __init__(self, name, price):
[Link] = name
[Link] = price
def show_details(self):
print("Movie name:", [Link], "and price:", [Link])
class PawanKalyanMovie(Movie):
def add_rating(self, rating):
[Link] = rating
def show_details(self):
print("Movie name:", [Link], "and price:", [Link], "rating:", [Link])
Data Science With Python Laboratory 10
R. RADHA KRISHNA N2000157
movie = PawanKalyanMovie("Gabbar Singh", 150)
movie.add_rating("8/10")
movie.show_details()
Output:
25. Write a Python Program on Polymorphism
class Movie:
def __init__(self, name, price):
[Link] = name
[Link] = price
def show_details(self):
print("Movie name:", [Link], "and price:", [Link])
class PawanKalyanMovie(Movie):
def show_details(self):
print("Movie name:", [Link], "and price:", [Link])
movie = PawanKalyanMovie("Gabbar Singh", 150)
movie.show_details()
Output:
26. Write a Python Program on Abstraction
class Movie:
def __init__(self, name, price):
[Link] = name
[Link] = price
def show_details(self):
pass
class PawanKalyanMovie(Movie):
def show_details(self):
print("Movie name:", [Link], "and price:", [Link])
movie = PawanKalyanMovie("Gabbar Singh", 150)
movie.show_details()
Output:
Data Science With Python Laboratory 11
R. RADHA KRISHNA N2000157
LAB -02
Files And Regular Expressions
1. Write a Python Program on Files and its Operations
# Create and write to a file
file = open("[Link]", "w")
[Link]("Hello, world!\n")
[Link]("This is a test file.\n")
[Link]("Writing some data to demonstrate file handling in Python.\n")
[Link]()
# Read from the file
print("Contents of the file:")
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
# Append to the file
file = open("[Link]", "a")
[Link]("Appending some more data to the file.\n")
[Link]()
# Read from the file after appending
print("\nContents of the file after appending:")
with open("[Link]","r") as f:
print([Link]())
print([Link]())
[Link](0)
print([Link](7))
Output:
2. Write a Python Program on Regular Expressions
import re
text = "Hello, world! This is a test string."
pattern = "world"
match = [Link](pattern, text)
Data Science With Python Laboratory 12
R. RADHA KRISHNA N2000157
if match:
print("Pattern found:", [Link]())
# Find all occurrences of digits in a string
text = "abc123def456ghi789"
pattern = r"\d+" # Match one or more digits
matches = [Link](pattern, text)
print("Digits found:", matches)
# Find all occurrences of vowels in a string
text = "apple banana orange"
pattern = r"[aeiou]+" # Match one or more vowels
matches = [Link](pattern, text)
print("Vowels found:", matches)
# Extract names from a comma-separated string
# Replace a pattern with a replacement string
text = "Hello, world! This is a test string."
pattern = r"world"
replacement = "Python"
new_text = [Link](pattern, replacement, text)
print("Modified text:", new_text)
Output:
Data Science With Python Laboratory 13
R. RADHA KRISHNA N2000157
LAB -03
Numpy , Pandas , Data Preprocessing And Web Scraping
1. Write a Python Program on Numpy and its methods
import numpy as np
# Creating an array
arr = [Link]([[1, 2, 3], [4, 5, 6]])
# Determining the shape of the array
print("Shape of the array:", [Link])
# Identifying the data type of elements
print("Data type of elements:", [Link])
# Calculating the total size of the array
print("Size of the array:", [Link])
# Reshaping the array
arr_reshaped = [Link](3, 2)
print("Array after reshaping:")
print(arr_reshaped)
# Finding the minimum value in the array
print("Minimum value in the array:", [Link]())
# Finding the maximum value in the n
print("Maximum value in the array:", [Link]())
# Computing the sum of all elements
print("Sum of all elements:", [Link]())
# Calculating the mean of all elements
print("Mean of all elements:", [Link]())
# Transposing the array
print("Transpose of the array:")
print(arr.T)
# Extracting the diagonal elements of the array
print("Diagonal elements of the array:", [Link](arr))
# Concatenating arrays
arr2 = [Link]([[7, 8, 9]])
concatenated_arr = [Link]((arr, arr2), axis=0)
print("Concatenated array:")
print(concatenated_arr)
# Performing element-wise multiplication
mul_arr = [Link](arr, 2)
Data Science With Python Laboratory 14
R. RADHA KRISHNA N2000157
print("Array after element-wise multiplication:")
print(mul_arr)
# Performing element-wise addition
add_arr = [Link](arr, 1)
print("Array after element-wise addition:")
print(add_arr)
# Computing the dot product of two arrays
arr3 = [Link]([[1, 0], [0, 1], [1, 1]])
dot_product = [Link](arr, arr3)
print("Dot product of two arrays:")
print(dot_product)
Output:
2. Write a Python Program on Pandas And Data Preprocessing
import pandas as pd
# Creating a Series
data_series = {'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14, 15]}
Data Science With Python Laboratory 15
R. RADHA KRISHNA N2000157
series = [Link](data_series['A'])
# Series methods
print("Series Methods:")
print("----------------")
# 1. head()
print("1. head():")
print([Link]())
print()
# 2. tail()
print("2. tail():")
print([Link]())
print()
# 3. describe()
print("3. describe():")
print([Link]())
print()
# 4. value_counts()
print("4. value_counts():")
print(series.value_counts())
print()
# 5. sum()
print("5. sum():", [Link]())
# 6. mean()
print("6. mean():", [Link]())
# 7. std()
print("7. std():", [Link]())
# 8. min()
print("8. min():", [Link]())
# 9. max()
print("9. max():", [Link]())
# 10. median()
print("10. median():", [Link]())
# 11. idxmax()
print("11. idxmax():", [Link]())
# 12. idxmin()
print("12. idxmin():", [Link]())
# 13. sort_values()
print("13. sort_values():")
print(series.sort_values())
print()
Data Science With Python Laboratory 16
R. RADHA KRISHNA N2000157
# 14. sort_index()
print("14. sort_index():")
print(series.sort_index())
print()
# 15. apply()
print("15. apply():")
print([Link](lambda x: x**2))
print()
# Creating a DataFrame
data_df = {'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14, 15]}
df = [Link](data_df)
# DataFrame methods
print("DataFrame Methods:")
print("-------------------")
# 1. head()
print("1. head():")
print([Link]())
print()
# 2. tail()
print("2. tail():")
print([Link]())
print()
# 3. describe()
print("3. describe():")
print([Link]())
print()
# 4. info()
print("4. info():")
print([Link]())
print()
# 5. shape
print("5. shape:", [Link])
# 6. columns()
print("6. columns():", [Link])
# 7. index()
print("7. index():", [Link])
# 8. mean()
print("8. mean():")
print([Link]())
print()
Data Science With Python Laboratory 17
R. RADHA KRISHNA N2000157
# 9. std()
print("9. std():")
print([Link]())
print()
# 10. min()
print("10. min():")
print([Link]())
print()
# 11. max()
print("11. max():")
print([Link]())
print()
# 12. median()
print("12. median():")
print([Link]())
print()
# 13. corr()
print("13. corr():")
print([Link]())
print()
# 14. dropna()
print("14. dropna():")
print([Link]())
print()
# 15. fillna()
print("15. fillna():")
print([Link](0))
Data Science With Python Laboratory 18
R. RADHA KRISHNA N2000157
Output:
3. Write a Python Program on Web Scraping
import requests
try:
url="[Link]
r=[Link](url)
print(r.status_code)
except:
print(r.status_code)
print("rejected")
Data Science With Python Laboratory 19
R. RADHA KRISHNA N2000157
pass
from bs4 import BeautifulSoup
soup = BeautifulSoup([Link], '[Link]')
# Find the div with class "table-responsive"
table_div = [Link]('div', class_='table-responsive')
# Extract the table from the div
table = table_div.find('table')
table_rows=table.find_all("tr")
college_List={
"rank":[],
"name":[],
"location":[]
}
for i in table_rows[2:-1]:
td=i.find_all("td")
# print(i)
try:
if(td[0].[Link]):
college_List["rank"].append(td[0].[Link])
except:
college_List["rank"].append(None)
try:
if(td[1].[Link]):
college_List["name"].append(td[1].[Link])
except:
college_List["name"].append(None)
try:
if(td[2].text):
college_List["location"].append(td[2].text)
except:
Data Science With Python Laboratory 20
R. RADHA KRISHNA N2000157
college_List["location"].append(None)
college_List
import pandas as pd
print(len(college_List['rank']))
print(len(college_List['name']))
print(len(college_List['location']))
data= [Link](college_List)
data
Output:
Data Science With Python Laboratory 21
R. RADHA KRISHNA N2000157
LAB-04
Linear ,Multiple and Polynomial Regression
1. Write a Python Program on Linear Regression
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('[Link]')
X = data[['X']].values y = data['y'].values
model = LinearRegression()
[Link](X, y)
y_predict = [Link](X)
# Plotting the results
[Link](X, y, color='blue', label='Data points')
[Link](X, y_predict, color='red', linewidth=2, label='Regression line')
[Link]('X')
[Link]('y')
[Link]('Linear Regression Example')
[Link]()
[Link]()
# Printing the model parameters
print(f'Intercept: {model.intercept_}')
print(f'Slope: {model.coef_[0]}')
Output:
2. Write a Python Program on Residual Plot
Data Science With Python Laboratory 22
R. RADHA KRISHNA N2000157
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('[Link]')
X = data[['X']].values # Ensure X is in the right shape for scikit-learn
y = data['y'].values
model = LinearRegression()
[Link](X, y)
y_predict = [Link](X)
residuals = y - y_predict
[Link](X, residuals, color='blue', label='Residuals')
[Link](y=0, color='red', linestyle='--', linewidth=2)
[Link]('X')
[Link]('Residuals')
[Link]('Residual Plot')
[Link]()
[Link]()
print(f'Intercept: {model.intercept_}')
print(f'Slope: {model.coef_[0]}')
Output:
3. Write a Python Program on Regression Plot
Data Science With Python Laboratory 23
R. RADHA KRISHNA N2000157
[Link](0)
X = 2 * [Link](100, 1)
y = 2 * X + 9+[Link](100, 1)
y_pred = [Link](X)
# Plotting the regression plot using Seaborn
[Link](x=[Link](), y=[Link](),scatter_kws={'color': "blue"}, line_kws={'color': 'yellow'})
[Link]('X')
[Link]('y')
[Link]('Regression Plot')
[Link]()
Output:
4. Write a Python Program on Distribution Plot
import seaborn as sns
import [Link] as plt
data = [0.1,3 ,0.5,1, 1.7, 1.9,2.0, 2.2, 2.5,3]
[Link](data, kde=True, color='violet', bins=8) # KDE adds a kernel density estimate line
[Link]('Distribution Plot')
[Link]('Values')
[Link]('Frequency')
[Link]()
Data Science With Python Laboratory 24
R. RADHA KRISHNA N2000157
Output:
[Link] a Python Program on Multi Linear Regression
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('[Link]')
X = data[['X']].values y = data['y'].values
model = LinearRegression()
[Link](X, y)
y_predict = [Link](X)
# Plotting the results
[Link](X, y, color='blue', label='Data points')
[Link](X, y_predict, color='red', linewidth=2, label='Regression line')
[Link]('X')
[Link]('y')
[Link]('Linear Regression Example')
[Link]()
[Link]()
# Printing the model parameters
print(f'Intercept: {model.intercept_}')
print(f'Slope: {model.coef_[0]}')
Output:
Data Science With Python Laboratory 25
R. RADHA KRISHNA N2000157
[Link] a Python Program on Polynomial Regression
import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import PolynomialFeatures
[Link](0)
X = 5* [Link](100, 1)
y = 8* X+[Link](100,1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
poly_features = PolynomialFeatures(degree=5)
X_train_poly = poly_features.fit_transform(X_train)
X_test_poly = poly_features.transform(X_test)
model = LinearRegression()
[Link](X_train_poly, y_train)
y_pred = [Link](X_test_poly)
X_plot = [Link](0, 2, 100).reshape(-1, 1)
X_plot_poly = poly_features.transform(X_plot)
y_plot = [Link](X_plot_poly)
[Link](X, y, label='Data')
[Link](X_plot, y_plot, color='green', label='Polynomial Regression')
[Link]('X')
[Link]('y')
[Link]('Polynomial Regression')
[Link]()
[Link]()
Output:
Data Science With Python Laboratory 26
R. RADHA KRISHNA N2000157
LAB-05
Data Visualization: Visualizing Data using different type of plotting techniques
[Link] a Python Program on Box Plot
import [Link] as plt
data =[2,4,6,3,1,4,5,2]
[Link](data)
Output:
2. Write a Python Program on Bubble Plot
import [Link] as plt
import numpy as np
n=30
x = [Link](n)
y = [Link](n)
sizes = [Link](n) * 1000
[Link](x, y, s=sizes)
Output:
Data Science With Python Laboratory 27
R. RADHA KRISHNA N2000157
[Link] a Python Program on Bar Plot
import [Link] as plt
import numpy as np
rajamouli_movies = ['Baahubali: The Beginning', 'Baahubali 2: The Conclusion', 'Eega',
'Magadheera', 'Chatrapathi']
ratings = [8.3, 8.4, 7.8, 7.9, 7.6]
[Link](rajamouli_movies, ratings, color=['blue', 'green', 'red', 'orange', 'purple'])
[Link]('S.S. Rajamouli Movies and Ratings')
[Link]('Movies')
[Link]('Ratings')
[Link](rotation=45)
[Link]()
Output:
#multibar
import [Link] as plt
import numpy as np
pk_movies = ['Jalsa', 'Kushi', 'Thammudu', 'Badri', 'Gabbar Singh', 'Attarintiki Daredi', 'Sardaar
Gabbar Singh', 'Katamarayudu', 'Agnyaathavaasi', 'Vakeel Saab']
child_ratings = [8.5, 8.0, 7.5, 7.0, 8.7, 9.2, 7.8, 7.3, 6.5, 8.9]
old_ratings = [7.5, 7.0, 6.5, 6.0, 7.7, 8.2, 6.8, 6.3, 5.5, 7.9]
bar_width = 0.35
index = [Link](len(pk_movies))
[Link](index, child_ratings, width=bar_width, label='Children')
[Link](index + bar_width, old_ratings, width=bar_width, label='Old people')
[Link]('Movies')
[Link]('Ratings')
[Link]('Pawan Kalyan Movies and Ratings by Audience Type')
[Link](index + bar_width / 2, pk_movies, rotation=45)
[Link]()
plt.tight_layout()
[Link]()
Data Science With Python Laboratory 28
R. RADHA KRISHNA N2000157
Output:
[Link] a Python Program on Histogram
import [Link] as plt
import numpy as np
data = [Link](30)*10
[Link](data, bins=15, edgecolor='black')
Output:
Data Science With Python Laboratory 29
R. RADHA KRISHNA N2000157
[Link] a Python Program on Pie chart
import [Link] as plt
icecream= ["Jalsa",
"Kushi",
"Thammudu",
"Badri",
"Gabbar Singh",
"Attarintiki Daredi",
"Sardaar Gabbar Singh",
"Katamarayudu",
"Agnyaathavaasi",
"Vakeel Saab"]
No_of_people = [20,50,10,20,14,17,30,30,50,10]
[Link](No_of_people,labels =icecream,shadow =
True,startangle=50,explode=[0.1,0,0.3,0,0,0,0,0,0,0])
Output:
Data Science With Python Laboratory 30
R. RADHA KRISHNA N2000157
LAB-06
Model Evaluation
[Link] a Python Program on Training And Testing and Predicting Data
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error
import numpy as np
X = 2* [Link](100, 1)
y = 50 + [Link](100)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
[Link](X_train, y_train)
y_pred = [Link](X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
ex=[[1.567]]
pred=[Link](ex)
print("Prediction: ",pred)
Output:
Data Science With Python Laboratory 31