PYTHON AND DATA
FUNDAMENTALS
[AY 2024-25]
PRACTICAL FILE
Submitted by –
Divyansh
BMS 1 C
24070
3
INDEX
4
5
6
PROGRAM 1.1
print("Hello world")
PROGRAM 1.2
a = 50
b = 10
print("The sum of two numbers is", a+b)
print("The subtraction of two numbers is", a-b)
print("The multiplication of two numbers is", a*b)
print("The division of two numbers is", a/b)
PROGRAM 2.1
p = int(input("Enter the principle amount: "))
r = int(input("Enter the rate of interest:"))
t = int(input("Enter the time period:"))
def simpleinterest(p,r,t):
SI = p + (p*r*t)/100
return SI
def compoundedinterest(p,r,t):
CI = p*(1+r/100)**t
return CI
print("The simple interest caluculetes to be",simpleinterest(p,r,t))
print("The Comp[ound Interest calculates to be",compoundedinterest(p,r,t))
7
PROGRAM 2.2
a = input("Enter the shape whose area you want to calculate (Circle/Square/Rectangle): ")
if a == "Circle":
r = int(input("Enter the radius of the circle: "))
area_r= 3.14*r*r
print("The area of the circle is",area_r)
elif a == "Square":
s = int(input("Enter the side of the square: "))
area_s = s**2
print("The area of the square is",area_s)
elif a == "Rectangle":
s2 = int(input("Enter the length of the rectangle: "))
s3 = int(input("Enter the breadth of the rectangle: "))
area_r = s2*s3
print("The area of the rectangle is",area_r)
else:
print("Invalid Input")
PROGRAM 3.1
a = int(input("Enter the number: "))
for i in range (0,11):
print(a,"X",i,"=",a*i)
8
PROGRAM 3.2
a = int(input("Enter the left value of the range: "))
b = int(input("Enter the right value of the range: "))
odd = 0
for i in range (a,b+1):
if i%2 != 0:
odd += 1
print("The number of odd numbers are",odd)
PROGRAM 3.3
a = int(input("Enter the left value of the range: "))
b = int(input("Enter the right value of the range: "))
even = 0
for i in range (a,b+1):
if i%2 == 0:
even += 1
print("The number of even numbers are",even)
PROGRAM 3.4
a = int(input("Enter the number: "))
b = int(input("Ente the power: "))
for i in range (0,b+1):
print(a,"^",i,"=",a**i)
9
PROGRAM 4.1
a = int(input("Enter the number: "))
if a%5 == 0:
print("The number is divisble by 5")
else:
print("The number is not divisible by 5")
PROGRAM 4.2
a = int(input("Enter the year you want to check: "))
if (a%4 == 0 and a%100 != 0) or (a%400 == 0):
print("The year is a leap year")
else:
print("The year is not a leap year")
PROGRAM 4.3
a = int(input("Enter your score: "))
if a >= 90:
print("Your grade is A")
elif a >= 80:
print("Your grade is B")
elif a>=60:
print("Your grade is C")
elif a>=40:
print("Your garde is D")
else:
print("You failed the test")
10
PROGRAM 5.1
a = int(input("Enter the weight of your baggage: "))
b = a - 20
if b<=0:
print("You are within the allowed limit")
elif b <=10:
print("You have to pay",b*1000,"rupees")
elif b <=20:
print("You have to pay",b*2000,"rupees")
elif b >20:
print("You have to pay",b*3000,"rupees")
PROGRAM 6.1
a = int(input("Enter the number: "))
i=0
while i<=10:
print(a,"X",i,"=",a*i)
i += 1
PROGRAM 6.2
a = int(input("Enter the value of n: "))
i=0
sum = 0
while i<=a:
sum += i
i += 1
print("The sum of first",a,"natural numbers is",sum)
11
PROGRAM 6.3
a = ''
b = "12345"
while a != b:
a = input("Enter the 5 digit password: ")
if a != b:
print("Wrong password")
else:
print("Correct Password")
PROGRAM 7.1
a= int(input("Enter a number: "))
multiple = 0
i=0
while i <=a:
if i%5 ==0:
multiple +=1
i+= 1
print("The number of multiples of 5 before" ,a,"is",multiple)
PROGRAM 8.1
def matrix_multiplication(A, B):
rows_A, cols_A = len(A), len(A[0])
rows_B, cols_B = len(B), len(B[0])
12
if cols_A != rows_B:
raise ValueError("Number of columns in A must be equal to number of rows in B.")
result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]
return result
A = [[1, 2, 3],
[4, 5, 6]]
B = [[7, 8],
[9, 10],
[11, 12]]
result = matrix_multiplication(A, B)
for row in result:
print(row)
PROGRAM 9.1
i=0
while i <6:
print("The square of",i,"is",i**2)
i+= 1
13
PROGRAM 9.2
a = []
b = input("Enter the age of 5 people")
c = list(map(int,b.split()))
a.extend(c)
count = 0
for i in a:
if i< 18:
count += 1
print("The number of people below 18 are",count)
PROGRAM 9.3
a = []
b = input("Enter the numbers to be added: ")
c = list(map(int,b.split()))
a.extend(c)
count = 0
sum = 0
for i in a:
sum += i
i+= 1
print("The sum of numbers is ",sum)
14
PROGRAM 10.1
lst_1 = [1,2,3,4,5]
lst_2 = [5,4,2,9,10]
a = set(lst_1)
b = set(lst_2)
lst_3 = list(a.symmetric_difference(b))
print("The required list is", lst_3)
PROGRAM 10.2
s = {1,2,3,4,5,8,9,10}
a = max(s)
b = min(s)
print("The maximum number is",a)
print("The minimum number is",b)
PROGRAM 10.3
l = [1,2,3,4,5,1,1]
a = list(set(l))
print("The unique numbers are",a)
15
PROGRAM 10.4
s1 = {1,2,3,4}
s2 = {5,6,7,8}
print("The statement that the sets are disjoint is",s1.isdisjoint(s2))
PROGRAM 10.5
def power_set(input_set):
result = [[]]
for element in input_set:
result += [subset + [element] for subset in result]
return result
input_set = [1, 2, 3]
print(power_set(input_set))
PROGRAM 10.6
dic = {'a':1,'b':2,'d':3,'c':4}
sort1 = dict(sorted(dic.items()))
sort2 = dict(sorted(dic.items(),key=lambda x:x[1]))
print(sort1)
print(sort2)
PROGRAM 11.1
l = ["Aditya","Aman","Raj","Aditya","Aman","Vanya","Bihar"]
count = {}
16
for i in l:
if i in count:
count[i] += 1
else:
count[i] = 1
print(count)
PROGRAM 11.2
d = {'a':1,'b':2,'c':3,'d':4}
c = max(d.keys())
print(The key with the max vakue is",c)
PROGRAM 11.3
a = [1,2,3,4]
b = [5,6,7,8]
c = dict(zip(a,b))
print(c)
PROGRAM 11.4
def reverse_sentence(sentence):
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words)
17
sentence = "Hello world this is Python"
print(reverse_sentence(sentence))
PROGRAM 11.5
def reverse_list(lst):
return lst[::-1]
print(reverse_list([1, 2, 3, 4]))
PROGRAM 11.6
def sort_list(lst):
return sorted(lst)
# Example usage
print(sort_list([4, 1, 3, 2]))
PROGRAM 12.1
def find_index(lst, target):
return lst.index(target) if target in lst else -1
print(find_index([10, 20, 30], 20))
PROGRAM 12.2
def to_uppercase(string):
return string.upper()
print(to_uppercase("hello"))
18
PROGRAM 12.3
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 3, 3]))
PROGRAM 12.4
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
PROGRAM 12.5
def add_a_to_itself(a, b):
return a * b
print(add_a_to_itself(3, 4))
PROGRAM 12.6
def sum_args(*args):
return sum(args)
print(sum_args(1, 2, 3, 4))
PROGRAM 12.7
def full_name(first, last):
return f"{first} {last}"
print(full_name("John", "Doe"))
19
PROGRAM 12.8
import math
def area_of_circle(radius):
return math.pi * radius ** 2
print(area_of_circle(5))
PROGRAM 13.1
class Interest:
def init (self, principal, rate, time):
self.principal = principal
self.rate = rate
self.time = time
def simple_interest(self):
return (self.principal * self.rate * self.time) / 100
def compound_interest(self):
return self.principal * ((1 + self.rate / 100) ** self.time) - self.principal
interest = Interest(1000, 5, 2)
print(interest.simple_interest())
print(interest.compound_interest())
PROGRAM 13.2
class Rectangle:
def init (self, length, width):
self.length = length
self.width = width
20
def area(self):
return self.length * self.width
rect = Rectangle(5, 4)
print(rect.area())
PROGRAM 14.1
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print(is_prime(7))
PROGRAM 14.2
def max_of_three(a, b, c):
return max(a, b, c)
print(max_of_three(5, 10, 3))
PROGRAM 15.1
def area_of_rectangle(length, width):
return length * width
import rectangle_module
print(rectangle_module.area_of_rectangle(5, 4))
21
PROGRAM 15.2
from datetime import datetime
def record_transaction(amount, description):
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return f"{date} - {description}: ${amount}"
print(record_transaction(100, "Deposit"))
PROGRAM 16.1
class AddNumbers:
def init (self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return self.num1 + self.num2
adder = AddNumbers(5, 3)
print(adder.add())
PROGRAM 17.1
import numpy as np
def positive_elements(arr):
return arr[arr > 0]
array = np.array([-1, 2, -3, 4])
print(positive_elements(array))
22
PROGRAM 18.1
import matplotlib.pyplot as plt
def bar_graph(x, y):
plt.bar(x, y)
plt.show()
bar_graph(['A', 'B', 'C'], [10, 20, 15])
PROGRAM 18.2
import matplotlib.pyplot as plt
def line_graph(x, y):
plt.plot(x, y)
plt.show()
line_graph([1, 2, 3], [10, 15, 20])
PROGRAM 18.3
import matplotlib.pyplot as plt
def pie_chart(labels, sizes):
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show()
pie_chart(['A', 'B', 'C'], [30, 50, 20])
23
PROGRAM 18.4
import matplotlib.pyplot as plt
def histogram(data, bins):
plt.hist(data, bins=bins)
plt.show()
histogram([1, 2, 2, 3, 3, 3, 4, 4, 5], bins=5)
PROGRAM 18.5
import matplotlib.pyplot as plt
def scatter_plot(x, y):
plt.scatter(x, y)
plt.show()
scatter_plot([1, 2, 3], [4, 5, 6])
PROGRAM 19.1
import pandas as pd
def read_csv(file_path):
return pd.read_csv(file_path)
df = read_csv('file.csv')
print(df)
PROGRAM 19.2
def overwrite_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
overwrite_file('example.txt', 'This is new content.')
24
PROGRAM 19.3
def filter_lines(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return [line for line in lines if line.startswith(('A', 'E'))]
filtered = filter_lines('example.txt')
print(filtered)
PROGRAM 20.1
import pandas as pd
def create_and_multiply(series_data):
series = pd.Series(series_data)
return series * 2
print(create_and_multiply([1, 2, 3]))
PROGRAM 20.2
import pandas as pd
def series_operations(series1, series2):
return series1 + series2, series1 - series2, series1 * series2, series1 / series2
s1 = pd.Series([1, 2, 3])
s2 = pd.Series([4, 5, 6])
print(series_operations(s1, s2))
PROGRAM 20.3
import pandas as pd
def create_dataframe(data, columns):
return pd.DataFrame(data, columns=columns)
25
data = [[1, 'Alice'], [2, 'Bob']]
columns = ['ID', 'Name']
print(create_dataframe(data, columns))
PROGRAM 20.4
import pandas as pd
def read_dataframe(file_path):
return pd.read_csv(file_path)
df = read_dataframe('file.csv')
print(df)
PROGRAM 20.5
import pandas as pd
def combine_dataframes(df1, df2):
return pd.concat([df1, df2])
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
print(combine_dataframes(df1, df2))
PROGRAM 20.6
import pandas as pd
def merge_dataframes(df1, df2, key):
return pd.merge(df1, df2, on=key)
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Score': [85, 90]})
print(merge_dataframes(df1, df2, 'ID'))
26
PROGRAM 20.7
import pandas as pd
def combine_common_rows(df1, df2):
return pd.merge(df1, df2, how='inner')
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Score': [85, 90]})
print(combine_common_rows(df1, df2))
PROGRAM 20.8
import pandas as pd
def outer_and_inner_merge(df1, df2):
outer = pd.merge(df1, df2, how='outer')
inner = pd.merge(df1, df2, how='inner')
return outer, inner
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Score': [85, 90]})
outer, inner = outer_and_inner_merge(df1, df2)
print("Outer Merge:\n", outer)
print("Inner Merge:\n", inner)
PROGRAM 20.9
import pandas as pd
def rename_columns_outer_join(df1, df2):
merged = pd.merge(df1, df2, how='outer')
merged.columns = ['Column1', 'Column2', 'Column3']
return merged
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Score': [85, 90]})
27
print(rename_columns_outer_join(df1, df2))
PROGRAM 20.10
import pandas as pd
def right_and_left_join(df1, df2):
left = pd.merge(df1, df2, how='left')
right = pd.merge(df1, df2, how='right')
return left, right
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Score': [85, 90]})
left, right = right_and_left_join(df1, df2)
print("Left Join:\n", left)
print("Right Join:\n", right)
PROGRAM 21.1
import pandas as pd
def dataframe_operations():
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Score': [85, 90, 95]}
df = pd.DataFrame(data)
max_score = df['Score'].max()
min_score = df['Score'].min()
mean_score = df['Score'].mean()
return max_score, min_score, mean_score
print(dataframe_operations())
28
PROGRAM 22.1
def is_palindrome(string):
return string == string[::-1]
print(is_palindrome("madam"))
print(is_palindrome("hello"))
PROGRAM 22.2
def primes_in_range(start, end):
primes = []
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
primes.append(num)
return primes
print(primes_in_range(10, 20))
29