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
3.Write 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)
li.append(4)
print(li)
m=[5,6,7]
li.extend(m)
print(li)
print(5 in li)
print(90 not in li)
li.remove(3)
print(li)
po=li.pop()
print(li)
print(po)
Data Science With Python Laboratory 3
R. RADHA KRISHNA N2000157
del li[0]
print(li)
li.clear()
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(d.get(2))
print(d.get(5))
d2={4:'gabbarsingh',5:'og'}
d.update(d2)
print(d)
print(d.keys())
print(d.values())
print(d.items())
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:
10.Write 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)
s.add(78)
print(s)
s.update((4,5))
print(s)
s.discard(3)
print(s)
print(s.union(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:", self.name)
print("Rating:", self.rating)
movie = Movie()
movie.name = "Gabbar Singh"
movie.rating = "8/10"
movie.show_details()
Output:
23.Write a Python Program on Constructors
class Movie:
def __init__(self, name, rating):
self.name = name
self.rating = rating
def show_details(self):
print("Movie name:", self.name)
print("Rating:", self.rating)
movie = Movie("Attarintiki Daredi", "9/10")
movie.show_details()
Output:
24 .Write a Python Program on Inheritance
class Movie:
def __init__(self, name, price):
self.name = name
self.price = price
def show_details(self):
print("Movie name:", self.name, "and price:", self.price)
class PawanKalyanMovie(Movie):
def add_rating(self, rating):
self.rating = rating
def show_details(self):
print("Movie name:", self.name, "and price:", self.price, "rating:", self.rating)
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):
self.name = name
self.price = price
def show_details(self):
print("Movie name:", self.name, "and price:", self.price)
class PawanKalyanMovie(Movie):
def show_details(self):
print("Movie name:", self.name, "and price:", self.price)
movie = PawanKalyanMovie("Gabbar Singh", 150)
movie.show_details()
Output:
26. Write a Python Program on Abstraction
class Movie:
def __init__(self, name, price):
self.name = name
self.price = price
def show_details(self):
pass
class PawanKalyanMovie(Movie):
def show_details(self):
print("Movie name:", self.name, "and price:", self.price)
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("example.txt", "w")
file.write("Hello, world!\n")
file.write("This is a test file.\n")
file.write("Writing some data to demonstrate file handling in Python.\n")
file.close()
# Read from the file
print("Contents of the file:")
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
# Append to the file
file = open("example.txt", "a")
file.write("Appending some more data to the file.\n")
file.close()
# Read from the file after appending
print("\nContents of the file after appending:")
with open("example.txt","r") as f:
print(f.read())
print(f.tell())
f.seek(0)
print(f.read(7))
Output:
2. Write a Python Program on Regular Expressions
import re
text = "Hello, world! This is a test string."
pattern = "world"
match = re.search(pattern, text)
Data Science With Python Laboratory 12
R. RADHA KRISHNA N2000157
if match:
print("Pattern found:", match.group())
# Find all occurrences of digits in a string
text = "abc123def456ghi789"
pattern = r"\d+" # Match one or more digits
matches = re.findall(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 = re.findall(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 = re.sub(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 = np.array([[1, 2, 3], [4, 5, 6]])
# Determining the shape of the array
print("Shape of the array:", arr.shape)
# Identifying the data type of elements
print("Data type of elements:", arr.dtype)
# Calculating the total size of the array
print("Size of the array:", arr.size)
# Reshaping the array
arr_reshaped = arr.reshape(3, 2)
print("Array after reshaping:")
print(arr_reshaped)
# Finding the minimum value in the array
print("Minimum value in the array:", arr.min())
# Finding the maximum value in the n
print("Maximum value in the array:", arr.max())
# Computing the sum of all elements
print("Sum of all elements:", arr.sum())
# Calculating the mean of all elements
print("Mean of all elements:", arr.mean())
# Transposing the array
print("Transpose of the array:")
print(arr.T)
# Extracting the diagonal elements of the array
print("Diagonal elements of the array:", np.diag(arr))
# Concatenating arrays
arr2 = np.array([[7, 8, 9]])
concatenated_arr = np.concatenate((arr, arr2), axis=0)
print("Concatenated array:")
print(concatenated_arr)
# Performing element-wise multiplication
mul_arr = np.multiply(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 = np.add(arr, 1)
print("Array after element-wise addition:")
print(add_arr)
# Computing the dot product of two arrays
arr3 = np.array([[1, 0], [0, 1], [1, 1]])
dot_product = np.dot(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 = pd.Series(data_series['A'])
# Series methods
print("Series Methods:")
print("----------------")
# 1. head()
print("1. head():")
print(series.head())
print()
# 2. tail()
print("2. tail():")
print(series.tail())
print()
# 3. describe()
print("3. describe():")
print(series.describe())
print()
# 4. value_counts()
print("4. value_counts():")
print(series.value_counts())
print()
# 5. sum()
print("5. sum():", series.sum())
# 6. mean()
print("6. mean():", series.mean())
# 7. std()
print("7. std():", series.std())
# 8. min()
print("8. min():", series.min())
# 9. max()
print("9. max():", series.max())
# 10. median()
print("10. median():", series.median())
# 11. idxmax()
print("11. idxmax():", series.idxmax())
# 12. idxmin()
print("12. idxmin():", series.idxmin())
# 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(series.apply(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 = pd.DataFrame(data_df)
# DataFrame methods
print("DataFrame Methods:")
print("-------------------")
# 1. head()
print("1. head():")
print(df.head())
print()
# 2. tail()
print("2. tail():")
print(df.tail())
print()
# 3. describe()
print("3. describe():")
print(df.describe())
print()
# 4. info()
print("4. info():")
print(df.info())
print()
# 5. shape
print("5. shape:", df.shape)
# 6. columns()
print("6. columns():", df.columns)
# 7. index()
print("7. index():", df.index)
# 8. mean()
print("8. mean():")
print(df.mean())
print()
Data Science With Python Laboratory 17
R. RADHA KRISHNA N2000157
# 9. std()
print("9. std():")
print(df.std())
print()
# 10. min()
print("10. min():")
print(df.min())
print()
# 11. max()
print("11. max():")
print(df.max())
print()
# 12. median()
print("12. median():")
print(df.median())
print()
# 13. corr()
print("13. corr():")
print(df.corr())
print()
# 14. dropna()
print("14. dropna():")
print(df.dropna())
print()
# 15. fillna()
print("15. fillna():")
print(df.fillna(0))
Data Science With Python Laboratory 18
R. RADHA KRISHNA N2000157
Output:
3. Write a Python Program on Web Scraping
import requests
try:
url="https://www.4icu.org/in/a-z/"
r=requests.get(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(r.text, 'html.parser')
# Find the div with class "table-responsive"
table_div = soup.find('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].b.text):
college_List["rank"].append(td[0].b.text)
except:
college_List["rank"].append(None)
try:
if(td[1].a.text):
college_List["name"].append(td[1].a.text)
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= pd.DataFrame(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 matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('data.csv')
X = data[['X']].values y = data['y'].values
model = LinearRegression()
model.fit(X, y)
y_predict = model.predict(X)
# Plotting the results
plt.scatter(X, y, color='blue', label='Data points')
plt.plot(X, y_predict, color='red', linewidth=2, label='Regression line')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression Example')
plt.legend()
plt.show()
# 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 matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('data.csv')
X = data[['X']].values # Ensure X is in the right shape for scikit-learn
y = data['y'].values
model = LinearRegression()
model.fit(X, y)
y_predict = model.predict(X)
residuals = y - y_predict
plt.scatter(X, residuals, color='blue', label='Residuals')
plt.axhline(y=0, color='red', linestyle='--', linewidth=2)
plt.xlabel('X')
plt.ylabel('Residuals')
plt.title('Residual Plot')
plt.legend()
plt.show()
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
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 2 * X + 9+np.random.randn(100, 1)
y_pred = model.predict(X)
# Plotting the regression plot using Seaborn
sns.regplot(x=X.flatten(), y=y.flatten(),scatter_kws={'color': "blue"}, line_kws={'color': 'yellow'})
plt.xlabel('X')
plt.ylabel('y')
plt.title('Regression Plot')
plt.show()
Output:
4. Write a Python Program on Distribution Plot
import seaborn as sns
import matplotlib.pyplot as plt
data = [0.1,3 ,0.5,1, 1.7, 1.9,2.0, 2.2, 2.5,3]
sns.histplot(data, kde=True, color='violet', bins=8) # KDE adds a kernel density estimate line
plt.title('Distribution Plot')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.show()
Data Science With Python Laboratory 24
R. RADHA KRISHNA N2000157
Output:
5.Write a Python Program on Multi Linear Regression
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = pd.read_csv('data.csv')
X = data[['X']].values y = data['y'].values
model = LinearRegression()
model.fit(X, y)
y_predict = model.predict(X)
# Plotting the results
plt.scatter(X, y, color='blue', label='Data points')
plt.plot(X, y_predict, color='red', linewidth=2, label='Regression line')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression Example')
plt.legend()
plt.show()
# 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
6.Write a Python Program on Polynomial Regression
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
np.random.seed(0)
X = 5* np.random.rand(100, 1)
y = 8* X+np.random.randn(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()
model.fit(X_train_poly, y_train)
y_pred = model.predict(X_test_poly)
X_plot = np.linspace(0, 2, 100).reshape(-1, 1)
X_plot_poly = poly_features.transform(X_plot)
y_plot = model.predict(X_plot_poly)
plt.scatter(X, y, label='Data')
plt.plot(X_plot, y_plot, color='green', label='Polynomial Regression')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Polynomial Regression')
plt.legend()
plt.show()
Output:
Data Science With Python Laboratory 26
R. RADHA KRISHNA N2000157
LAB-05
Data Visualization: Visualizing Data using different type of plotting techniques
1.Write a Python Program on Box Plot
import matplotlib.pyplot as plt
data =[2,4,6,3,1,4,5,2]
plt.boxplot(data)
Output:
2. Write a Python Program on Bubble Plot
import matplotlib.pyplot as plt
import numpy as np
n=30
x = np.random.rand(n)
y = np.random.rand(n)
sizes = np.random.rand(n) * 1000
plt.scatter(x, y, s=sizes)
Output:
Data Science With Python Laboratory 27
R. RADHA KRISHNA N2000157
3.Write a Python Program on Bar Plot
import matplotlib.pyplot 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]
plt.bar(rajamouli_movies, ratings, color=['blue', 'green', 'red', 'orange', 'purple'])
plt.title('S.S. Rajamouli Movies and Ratings')
plt.xlabel('Movies')
plt.ylabel('Ratings')
plt.xticks(rotation=45)
plt.show()
Output:
#multibar
import matplotlib.pyplot 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 = np.arange(len(pk_movies))
plt.bar(index, child_ratings, width=bar_width, label='Children')
plt.bar(index + bar_width, old_ratings, width=bar_width, label='Old people')
plt.xlabel('Movies')
plt.ylabel('Ratings')
plt.title('Pawan Kalyan Movies and Ratings by Audience Type')
plt.xticks(index + bar_width / 2, pk_movies, rotation=45)
plt.legend()
plt.tight_layout()
plt.show()
Data Science With Python Laboratory 28
R. RADHA KRISHNA N2000157
Output:
4.Write a Python Program on Histogram
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(30)*10
plt.hist(data, bins=15, edgecolor='black')
Output:
Data Science With Python Laboratory 29
R. RADHA KRISHNA N2000157
5.Write a Python Program on Pie chart
import matplotlib.pyplot 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]
plt.pie(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
1.Write 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 sklearn.metrics import mean_squared_error
import numpy as np
X = 2* np.random.rand(100, 1)
y = 50 + np.random.randn(100)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
ex=[[1.567]]
pred=model.predict(ex)
print("Prediction: ",pred)
Output:
Data Science With Python Laboratory 31