3.
PROGRAMS USING FUNCTIONS AND CLASSES:
class BankAccount:
def __init__(self, name, balance=0):
[Link] = name
[Link] = balance
def deposit(self, amount):
[Link] += amount
print(f"{amount} deposited successfully.")
def withdraw(self, amount):
if amount > [Link]:
print("Insufficient balance!")
else:
[Link] -= amount
print(f"{amount} withdrawn successfully.")
def display_balance(self):
print(f"Account Holder: {[Link]}")
print(f"Current Balance: {[Link]}")
# Function to interact with user
def bank_menu():
name = input("Enter account holder name: ")
account = BankAccount(name)
while True:
print("\n--- Bank Menu ---")
print("1. Deposit")
print("2. Withdraw")
print("3. Check Balance")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
amount = float(input("Enter amount to deposit: "))
[Link](amount)
elif choice == "2":
amount = float(input("Enter amount to withdraw: "))
[Link](amount)
elif choice == "3":
account.display_balance()
elif choice == "4":
print("Thank you for using the bank system!")
break
else:
print("Invalid choice! Please try again.")
# Main function
def main():
bank_menu()
# Run the program
if __name__ == "__main__":
main()
OUTPUT:
Enter account holder name: UUUU
--- Bank Menu ---
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 2
Invalid choice! Please try again.
--- Bank Menu ---
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 1
Enter amount to deposit: 1000
1000.0 deposited successfully.
--- Bank Menu ---
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 2
Enter amount to withdraw: 500
500.0 withdrawn successfully.
[Link] USING STRINGS AND FILES:
filename = "[Link]"
# 1. Write to file
text = input("Enter text to write into file: ")
with open(filename, "w") as file:
[Link](text)
print("Text written to file.\n")
# 2. Read file
with open(filename, "r") as file:
content = [Link]()
print("File content:")
print(content)
# 3. Count words
words = [Link]()
print("\nNumber of words:", len(words))
# 4. Count vowels
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in content if char in vowels)
print("Number of vowels:", vowel_count)
# 5. Append text
append_text = input("\nEnter text to append: ")
with open(filename, "a") as file:
[Link]("\n" + append_text)
print("Text appended successfully.")
# 6. Replace word
old_word = input("\nEnter word to replace: ")
new_word = input("Enter new word: ")
with open(filename, "r") as file:
content = [Link]()
updated_content = [Link](old_word, new_word)
with open(filename, "w") as file:
[Link](updated_content)
print("Word replaced successfully.")
# 7. Final content display
with open(filename, "r") as file:
final_content = [Link]()
print("\nFinal file content:")
print(final_content)
OUTPUT:
Enter text to write into file: Hello this is a sample file
Text written to file.
File content:
Hello this is a sample file
Number of words: 6
Number of vowels: 10
Enter text to append: This is added later
Text appended successfully.
Enter word to replace: sample
Enter new word: demo
Word replaced successfully.
Final file content:
Hello this is a demo file
This is added later
[Link] CREATION AND MATHEMATICAL OPERATIONS:
# Create a file and perform mathematical operations
filename = "[Link]"
# 1. Create data (write numbers into file)
n = int(input("Enter how many numbers: "))
numbers = []
for i in range(n):
num = int(input(f"Enter number {i+1}: "))
[Link](num)
with open(filename, "w") as file:
for num in numbers:
[Link](str(num) + " ")
print("\nNumbers stored in file.")
# 2. Read data from file
with open(filename, "r") as file:
data = [Link]()
nums = list(map(int, [Link]()))
# 3. Mathematical operations
total = sum(nums)
average = total / len(nums)
maximum = max(nums)
minimum = min(nums)
# 4. Display results
print("\nNumbers in file:", nums)
print("Sum =", total)
print("Average =", average)
print("Maximum =", maximum)
print("Minimum =", minimum)
OUTPUT:
Enter how many numbers: 5
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Numbers stored in file.
Numbers in file: [10, 20, 30, 40, 50]
Sum = 150
Average = 30.0
Maximum = 50
Minimum = 10
[Link] AND PLOTTING
import [Link] as plt
filename = "[Link]"
# 1. Create data and store in file
n = int(input("Enter number of data points: "))
x = []
y = []
for i in range(n):
xi = int(input(f"Enter x{i+1}: "))
yi = int(input(f"Enter y{i+1}: "))
[Link](xi)
[Link](yi)
with open(filename, "w") as file:
for i in range(n):
[Link](f"{x[i]} {y[i]}\n")
print("\nData stored in file.")
# 2. Read data from file
x_vals = []
y_vals = []
with open(filename, "r") as file:
for line in file:
xi, yi = map(int, [Link]())
x_vals.append(xi)
y_vals.append(yi)
# 3. Plot graph
[Link](x_vals, y_vals, marker='o', color='blue')
[Link]("X vs Y Graph")
[Link]("X values")
[Link]("Y values")
[Link](True)
[Link]()
OUTPUT: Enter number of data points: 4
Enter x1: 1
Enter y1: 2
Enter x2: 2
Enter y2: 4
Enter x3: 3
Enter y3: 6
Enter x4: 4
Enter y4: 8
Data stored in file.
[Link] DESCRIPTION OF DATA WITHOUT LIBRARIES GENERATION
OF CORRELATION COEFFICIENT
# Statistical description and correlation coefficient without libraries
# Input data
n = int(input("Enter number of data points: "))
x = []
y = []
print("\nEnter values for X:")
for i in range(n):
[Link](float(input(f"x{i+1}: ")))
print("\nEnter values for Y:")
for i in range(n):
[Link](float(input(f"y{i+1}: ")))
# Mean
mean_x = sum(x) / n
mean_y = sum(y) / n
# Variance and Standard Deviation
var_x = sum((xi - mean_x) ** 2 for xi in x) / n
var_y = sum((yi - mean_y) ** 2 for yi in y) / n
std_x = var_x ** 0.5
std_y = var_y ** 0.5
# Covariance
cov_xy = sum((x[i] - mean_x) * (y[i] - mean_y) for i in range(n)) / n
# Correlation Coefficient (Karl Pearson)
correlation = cov_xy / (std_x * std_y)
# Output results
print("\n--- Statistical Results ---")
print("Mean of X =", mean_x)
print("Mean of Y =", mean_y)
print("Variance of X =", var_x)
print("Variance of Y =", var_y)
print("Standard Deviation of X =", std_x)
print("Standard Deviation of Y =", std_y)
print("Covariance =", cov_xy)
print("Correlation Coefficient (r) =", correlation)
OUTPUT:
Enter number of data points: 4
Enter values for X:
x1: 1
x2: 2
x3: 3
x4: 4
Enter values for Y:
y1: 2
y2: 4
y3: 6
y4: 8
--- Statistical Results ---
Mean of X = 2.5
Mean of Y = 5.0
Variance of X = 1.25
Variance of Y = 5.0
Standard Deviation of X = 1.118
Standard Deviation of Y = 2.236
Covariance = 2.5
Correlation Coefficient (r) = 1.0
[Link] REGRESSION MODEL:
# Linear Regression without libraries
# Input data
n = int(input("Enter number of data points: "))
x = []
y = []
print("\nEnter values for X:")
for i in range(n):
[Link](float(input(f"x{i+1}: ")))
print("\nEnter values for Y:")
for i in range(n):
[Link](float(input(f"y{i+1}: ")))
# Calculate sums
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(x[i] * y[i] for i in range(n))
sum_x2 = sum(xi ** 2 for xi in x)
# Calculate slope (b) and intercept (a)
b = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
a = (sum_y - b * sum_x) / n
# Output equation
print("\n--- Linear Regression Model ---")
print(f"Equation of line: y = {a:.2f} + {b:.2f}x")
# Predict value
xp = float(input("\nEnter value of x to predict y: "))
yp = a + b * xp
print(f"Predicted value of y = {yp:.2f}")
OUTPUT:
Enter number of data points: 4
Enter values for X:
x1: 1
x2: 2
x3: 3
x4: 4
Enter values for Y:
y1: 2
y2: 4
y3: 6
y4: 8
--- Linear Regression Model ---
Equation of line: y = 0.00 + 2.00x
Enter value of x to predict y: 5
Predicted value of y = 10.00
[Link] OF ID,2D AND 3D NUMPY ARRAYS,ARRAY SLICING AND
INDEXING OPERATIONS,REINDEXING AND ALIGNING DATA ACROSS
MULTIPLE DATA FRAMES:
import numpy as np
import pandas as pd
# -------- 1. Create Arrays --------
print("1D Array:")
arr1 = [Link]([10, 20, 30, 40, 50])
print(arr1)
print("\n2D Array:")
arr2 = [Link]([[1, 2, 3],
[4, 5, 6]])
print(arr2)
print("\n3D Array:")
arr3 = [Link]([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]])
print(arr3)
# -------- 2. Slicing and Indexing --------
print("\n--- Slicing & Indexing ---")
print("First element of 1D array:", arr1[0])
print("Last element of 1D array:", arr1[-1])
print("\nElement from 2D array (row 1, col 2):", arr2[1, 2])
print("First row of 2D array:", arr2[0])
print("Second column of 2D array:", arr2[:, 1])
print("\nSlice 1D array (index 1 to 3):", arr1[1:4])
# -------- 3. Pandas DataFrames --------
print("\n--- DataFrames ---")
data1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df1 = [Link](data1, index=['a', 'b', 'c'])
print("\nDataFrame 1:")
print(df1)
data2 = {'A': [10, 20], 'B': [30, 40]}
df2 = [Link](data2, index=['b', 'c'])
print("\nDataFrame 2:")
print(df2)
# -------- 4. Reindexing --------
print("\n--- Reindexing ---")
df_reindexed = [Link](['a', 'b', 'c', 'd'])
print(df_reindexed)
# -------- 5. Aligning DataFrames --------
print("\n--- Aligning DataFrames ---")
df_add = df1 + df2
print(df_add)
OUTPUT:
1D Array:
[10 20 30 40 50]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
--- Slicing & Indexing ---
First element of 1D array: 10
Last element of 1D array: 50
Element from 2D array (row 1, col 2): 6
First row of 2D array: [1 2 3]
Second column of 2D array: [2 5]
Slice 1D array (index 1 to 3): [20 30 40]
--- DataFrames ---
DataFrame 1:
A B
a 1 4
b 2 5
c 3 6
DataFrame 2:
A B
b 10 30
c 20 40
--- Reindexing ---
A B
a 1.0 4.0
b 2.0 5.0
c 3.0 6.0
d NaN NaN
--- Aligning DataFrames ---
A B
a NaN NaN
b 12.0 35.0
c 23.0 46.0
[Link] [Link] PLOT,HISTOGRAM AND BOX PLOT,SEABORNPLOTS,PLOT
STYLING AND CUSTOMIZATION
import [Link] as plt
import seaborn as sns
import numpy as np
# -------- Sample Data --------
x = [Link]([1, 2, 3, 4, 5])
y = [Link]([2, 4, 6, 8, 10])
categories = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 3, 8, 6]
# -------- 1. Line Plot --------
[Link](figsize=(8,5))
[Link](x, y, marker='o', linestyle='-', color='blue', label='Line Plot')
[Link]("Line Plot Example")
[Link]("X-axis")
[Link]("Y-axis")
[Link](True)
[Link]()
[Link]()
# -------- 2. Bar Plot --------
[Link](figsize=(8,5))
[Link](categories, values, color='green', edgecolor='black')
[Link]("Bar Plot Example")
[Link]("Categories")
[Link]("Values")
[Link]()
# -------- 3. Histogram --------
data = [Link](50, 10, 100) # 100 random numbers, mean=50, std=10
[Link](figsize=(8,5))
[Link](data, bins=10, color='orange', edgecolor='black')
[Link]("Histogram Example")
[Link]("Value")
[Link]("Frequency")
[Link]()
# -------- 4. Box Plot --------
[Link](figsize=(8,5))
[Link](data, patch_artist=True, boxprops=dict(facecolor='cyan'))
[Link]("Box Plot Example")
[Link]("Values")
[Link]()
# -------- 5. Seaborn Plots --------
[Link](style="whitegrid") # Set style
# Scatter Plot
[Link](figsize=(8,5))
[Link](x=x, y=y, s=100, color='red')
[Link]("Seaborn Scatter Plot")
[Link]()
# Bar Plot using Seaborn
[Link](figsize=(8,5))
[Link](x=categories, y=values, palette="viridis")
[Link]("Seaborn Bar Plot")
[Link]()
OUTPUT: