0% found this document useful (0 votes)
39 views11 pages

LabManual(BDS306B)

The document is a lab manual for a Python programming course focused on data science, containing various exercises and scripts. It includes tasks such as reading integers, sorting numbers, calculating statistical measures, and handling CSV and HTML files. Each task is accompanied by code snippets and expected outputs to guide students in their programming practice.

Uploaded by

Pra Nav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views11 pages

LabManual(BDS306B)

The document is a lab manual for a Python programming course focused on data science, containing various exercises and scripts. It includes tasks such as reading integers, sorting numbers, calculating statistical measures, and handling CSV and HTML files. Each task is accompanied by code snippets and expected outputs to guide students in their programming practice.

Uploaded by

Pra Nav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab ManualPython Programming for DataScience(BDS306B)

1.Develop a python program to read n digit integer number, and separate the integer
number and display each digit. [Hint: input:5678 output: 5 6 7 8, use: floor and mod
operators)

# Read an n-digit integer


n = int(input("Enter the number of digits: "))
if n > 0:
number = int(input(f"Enter a {n}-digit integer: "))

# Check if the entered number has n digits


if number >= 10 ** (n - 1) and number < 10 ** n:
# Separate and display each digit using floor and mod operators
for _ in range(n):
digit = number // (10 ** (n - 1))
print(digit, end=' ')
number %= 10 ** (n - 1)
n -= 1
else:
print(f"Please enter a {n}-digit integer.")
else:
print("Please enter a valid number of digits (greater than 0).")

Output:

2.Develop a python program to accept 4 numbers and display them in sorted order using a
minimum number of if else statements.

# Accept 4 numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
num4 = int(input("Enter the fourth number: "))

# Sort the numbers using if-else statements


if num1 > num2:
num1, num2 = num2, num1
if num2 > num3:

CSE(DataScience) Page 1
Lab ManualPython Programming for DataScience(BDS306B)

num2, num3 = num3, num2


if num3 > num4:
num3, num4 = num4, num3
if num1 > num2:
num1, num2 = num2, num1
if num2 > num3:
num2, num3 = num3, num2
if num1 > num2:
num1, num2 = num2, num1

# Display the sorted numbers


print("Numbers in sorted order:")
print(num1, num2, num3, num4)

Output:

3.Develop a python script to rotate right about a given position in that list and display them.
#[hint: input [1,4,5,-10] position: 2, output: [-10,5,4,1]]

# Create a List
myList =[1,4,5,-10]

print("List before rotation = ",myList)

# The value of n for rotation position


n=int(input("Enter rotation position:"))

# Rotating the List


if n>len(myList):
n = int(n%len(myList))
myList = (myList[-n:] + myList[:-n])

# Display the Update List after rotation


print("Updated List after rotation = ",myList)

CSE(DataScience) Page 2
Lab ManualPython Programming for DataScience(BDS306B)

Output:

4.Develop python scripts to Calculate the mean, median, mode, variance and standard
deviation of n integer numbers.

# Accept n numbers from the user


n = int(input("Enter the number of elements: "))
numbers = [int(input(f"Enter number {i + 1}: ")) for i in range(n)]

# Calculate Mean
mean = sum(numbers) / n

# Calculate Median
numbers.sort()
if n % 2 == 0:
median = (numbers[n // 2 - 1] + numbers[n // 2]) / 2
else:
median = numbers[n // 2]

# Calculate Mode
frequency = {num: numbers.count(num) for num in numbers}
max_count = max(frequency.values())
mode = [k for k, v in frequency.items() if v == max_count]

if len(mode) == n: # No mode if all numbers appear the same number of times


mode = "No mode"

# Calculate Variance (Sample Variance, divide by (n-1))


mean_difference_squared_sum = sum((x - mean) ** 2 for x in numbers)
variance_sample = mean_difference_squared_sum / (n - 1) if n > 1 else 0 # Avoid division by 0
variance_population = mean_difference_squared_sum / n

# Calculate Standard Deviation


std_deviation_sample = variance_sample ** 0.5
std_deviation_population = variance_population ** 0.5

CSE(DataScience) Page 3
Lab ManualPython Programming for DataScience(BDS306B)

# Display results
print(f"Mean: {mean}")
print(f"Median: {median}")
print(f"Mode: {mode}")
print(f"Sample Variance: {variance_sample}")
print(f"Population Variance: {variance_population}")
print(f"Sample Standard Deviation: {std_deviation_sample}")
print(f"Population Standard Deviation: {std_deviation_population}")

Output:

5.Develop a program for checking if given n digit number is palindrome or not.[hint:input


1221 output: Palindrome,use //and % operator with loop statement]

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
digit=n%10 # Get the last digit
rev=rev*10+digit # Build the reversed number
n=n//10 # Remove the last digit from the number
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

Output:

CSE(DataScience) Page 4
Lab ManualPython Programming for DataScience(BDS306B)

6.Develop a python script to display a multiplication table for given integer n.

number = int(input ("Enter the number of which the user wants to print the
multiplication table: "))
# We are using "for loop" to iterate the multiplication 10 times
print ("The Multiplication Table of: ", number)
for count in range(1, 11):
print (number, 'x', count, '=', number * count)

Output:

7. Develop write a python script to interchange the digits of a given integer number.
[hint: input: 23456, interchange: 3 and 5 output: 25436]

n=int(input("Enter the number:"))


#convert the given number into string and then into list
digits = list(str(n))

n1=int(input("Enter first position for interchange:"))


n2=int(input("Enter second position for interchange:"))
#swap the given digits in the list at the given indices
digits[n1], digits[n2] = digits[n2], digits[n1]
#Convert the list back to an integer
result = int(''.join(digits))
print(f"Input: {n}, Interchanged: {result}")

Output:

CSE(DataScience) Page 5
Lab ManualPython Programming for DataScience(BDS306B)

8. Develop a python program to capitalize a given list of strings. [hint: [hello, good, how, simple]
output: [Hello, Good, How, Simple]

def capitalize_strings(string_list):
# Capitalize each string in the list
return [s.capitalize() for s in string_list]
'''The capitalize() function in Python is used to capitalize the first letter of a string. '''
# Example usage
input_strings = ['hello', 'good', 'how', 'simple']
capitalized_strings = capitalize_strings(input_strings)
print(capitalized_strings)

Output:

9.Using a dictionary, develop a python program to determine and print the number of duplicate
words in a sentence.

def count_duplicate_words(sentence):
# Split the sentence into words
words = sentence.split()

# Create a dictionary to store word counts


word_count = {}

# Count occurrences of each word


for word in words:
# Convert to lowercase for case-insensitivity
word = word.lower()
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1

# Find and print duplicate words


duplicates = {word: count for word, count in word_count.items() if count > 1}

if duplicates:
print("Duplicate words and their counts:")

CSE(DataScience) Page 6
Lab ManualPython Programming for DataScience(BDS306B)

for word, count in duplicates.items():


print(f"{word}: {count}")
else:
print("No duplicate words found.")

# Example usage
sentence = input("Enter a sentence: ")
count_duplicate_words(sentence)

Output:

10.Develop python program to read Numpy array and print row (sum,mean std) and
column(sum,mean,std)

import numpy as np

# define data as a list


data = [[1,2,3], [4,5,6]]
# convert to a numpy array
data = np.array(data)
# summarize the array content
print("Numpy Array")
print(data)
print("__________________________________________")
# sum data by row & column
totalr = data.sum(axis=1)
totalc = data.sum(axis=0)
# summarize the result
print("Row Sum")
print(totalr)
print("Column Sum")
print(totalc)
print("__________________________________________")
meanr = data.mean(axis=1)
meanc = data.mean(axis=0)
print("Row Mean")

CSE(DataScience) Page 7
Lab ManualPython Programming for DataScience(BDS306B)

print(meanr)
print("Column Mean")
print(meanc)
print("__________________________________________")
stdr = data.std(axis=1)
stdc = data.std(axis=0)
print("Row STD")
print(stdr)
print("Column STD")
print(stdc)

Output:

11.Develop a python program to read and print in the #console CSV file.

CSV file:
file name: employee_birthday.csv

name ,department, birthday_month


John Smith ,Accounting ,november
Erica Meyers, IT, march
Rocky, HR ,april

CSE(DataScience) Page 8
Lab ManualPython Programming for DataScience(BDS306B)

Program11.py
import csv
with open('employee_birthday.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
line_count += 1
print(f'Processed {line_count} lines.')

Output:

12.Develop a python program to read a HTML file with basic#tags, and construct a dictionary
and display the same in the console.

# Writing a simple HTML file with a table


html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Sample HTML with Table</title>
</head>
<body>
<h1>Employee Information</h1>
<table>
<tr>
<th>Name</th>
<th>Age</th>

CSE(DataScience) Page 9
Lab ManualPython Programming for DataScience(BDS306B)

<th>Department</th>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
<td>HR</td>
</tr>
<tr>
<td>Bob</td>
<td>25</td>
<td>IT</td>
</tr>
<tr>
<td>Charlie</td>
<td>35</td>
<td>Finance</td>
</tr>
</table>
</body>
</html>
"""

# Save the HTML content to a file


with open("table.html", "w") as file:
file.write(html_content)

print("HTML file 'table.html' has been created.")

#-----------------------------------------------------------------------
#output:HTML file 'table.html' has been created.
#---------------------------------------------------------------------------

import pandas as pd

def read_html_to_dict(html_file):
# Read all tables from the HTML file
tables = pd.read_html(html_file)

CSE(DataScience) Page 10
Lab ManualPython Programming for DataScience(BDS306B)

# Initialize an empty dictionary to store each table


tables_dict = {}

# Loop over each table and convert it to a dictionary


for i, table in enumerate(tables):
# Convert the DataFrame to a dictionary(each table
#will be its own dictionary entry)
table_dict = table.to_dict(orient='list')
'''orient='list' specifies that each column of the
DataFrame should be converted into a key in
the dictionary, with its values as a list of
items.'''
tables_dict[f'Table_{i+1}'] = table_dict

return tables_dict

if __name__ == '__main__':
html_file = 'table.html' # Replace with your HTML file path
result = read_html_to_dict(html_file)

# Display the dictionary


print(result)

Output:
{'Table_1': {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [30, 25, 35], 'Department': ['HR', 'IT',
'Finance']}}

CSE(DataScience) Page 11

You might also like