sib.
display_balance(customer_id)
elif opt == 5:
amount = int(input("Enter amount: "))
Bank.calculate_annual_interest(amount)
else:
break
elif x == 2:
while True:
opt = int(input("---ADMIN MENU---\n1. Update Interest\n2.
Return to main menu\nEnter option number: "))
if opt == 1:
new_rate = int(input("Enter new interest rate: "))
sib.update_interest_rate(new_rate)
else:
break
else:
break
Choose 1 for customer menu, 2 for Admin menu and 3 to Exit: 1
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 1
Enter a new customer id: 1001
Enter Name: John
Enter initial deposit: 20000
Do you want a Premium Account (1. Yes 2. No): 1
No sufficient balance for premium account, basic account created
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 1
Enter a new customer id: 200000
Enter Name: mathew
Enter initial deposit: 200000
Do you want a Premium Account (1. Yes 2. No): 1
Bonus of 1000 credited to mathew. New balance: 201000.
Premiun account created
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 2
Enter your customer id: 1001
Enter amount to be deposited: 200
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 4
Enter your customer id: 1001
20200
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 3
Enter your customer id: 200000
Enter amount to be withdrawn: 100
Withdrawal of Rs. 100 was successful
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 4
Enter your customer id: 200000
200900
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 6
Choose 1 for customer menu, 2 for Admin menu and 3 to Exit: 2
---ADMIN MENU---
1. Update Interest
2. Return to main menu
Enter option number: 1
Enter new interest rate: 6
Successfully updated interest rate
---ADMIN MENU---
1. Update Interest
2. Return to main menu
Enter option number: 2
Choose 1 for customer menu, 2 for Admin menu and 3 to Exit: 1
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 5
Enter amount: 20000
Annual Interest: 1200.0
---CUSTOMER MENU---
1. Create Account
2. Deposit Amount
3. Withdraw Amount
4. Display Balance
5. Calculate Interest for an amount
6. Return to main menu
Enter option number: 6
Choose 1 for customer menu, 2 for Admin menu and 3 to Exit: 3
Day 5 Program 2
class Item:
def __init__(self, item_name, price, quantity):
self.item_name = item_name
self.price = price
self.quantity = quantity
def get_total_price(self):
return self.price * self.quantity
def get_details(self):
return f"Item: {self.item_name}, Price: {self.price},
Quantity: {self.quantity}"
class PhysicalItem(Item):
def __init__(self, item_name, price, quantity, shipping_cost):
super().__init__(item_name, price, quantity)
self.shipping_cost = shipping_cost
def get_total_price(self):
return super().get_total_price() + self.shipping_cost
def get_details(self):
return f"Physical Item: {self.item_name}, Price: {self.price},
Quantity: {self.quantity}, Shipping Cost: {self.shipping_cost}"
class DigitalItem(Item):
def __init__(self, item_name, price, quantity, license_fee):
super().__init__(item_name, price, quantity)
self.license_fee = license_fee
def get_total_price(self):
return super().get_total_price() + self.license_fee
def get_details(self):
return f"Digital Item: {self.item_name}, Price: {self.price},
Quantity: {self.quantity}, License Fee: {self.license_fee}"
class ShoppingCart:
tax_rate = 0.05
def __init__(self):
self.cart_items = {}
def add_item(self, item_name, price, quantity):
if price < 0 or quantity < 0:
raise ValueError("Price and quantity must be non-
negative.")
if item_name not in self.cart_items:
self.cart_items[item_name] = {'price': price, 'quantity':
quantity}
else:
self.cart_items[item_name]['quantity'] += quantity
def remove_item(self, item_name, quantity):
if item_name not in self.cart_items:
raise KeyError(f"Item '{item_name}' not found in cart.")
if quantity <= 0:
raise ValueError("Quantity to remove must be positive.")
if self.cart_items[item_name]['quantity'] <= quantity:
del self.cart_items[item_name]
else:
self.cart_items[item_name]['quantity'] -= quantity
def calculate_total(self):
total = 0
for item_name, item_info in self.cart_items.items():
total += item_info['price'] * item_info['quantity']
total_with_tax = total * (1 + self.tax_rate)
return total_with_tax
def display_cart(self):
if not self.cart_items:
print("Cart is empty.")
return
for item_name, item_info in self.cart_items.items():
print(f"Item: {item_name}, Price: {item_info['price']},
Quantity: {item_info['quantity']}")
@classmethod
def update_tax_rate(cls, new_rate):
if new_rate < 0:
raise ValueError("Tax rate cannot be negative.")
cls.tax_rate = new_rate
@staticmethod
def apply_discount(total, discount):
if discount < 0 or discount > 100:
raise ValueError("Discount must be between 0 and 100.")
discount_amount = total * (discount / 100)
return total - discount_amount
def __del__(self):
print("Shopping cart deleted.")
def get_float_input(prompt):
while True:
try:
value = float(input(prompt))
if value < 0:
print("Please enter a non-negative value.")
else:
return value
except ValueError:
print("Invalid input, please enter a valid number.")
def user_interaction():
cart = ShoppingCart()
while True:
print("\n--- Shopping Cart Menu ---")
print("1. Add Item")
print("2. Remove Item")
print("3. Display Cart")
print("4. Update Tax Rate")
print("5. Calculate Total")
print("6. Apply Discount")
print("7. Exit")
choice = input("Choose an option (1-7): ")
if choice == '1':
item_name = input("Enter item name: ")
price = get_float_input("Enter item price: ")
quantity = int(input("Enter item quantity: "))
try:
cart.add_item(item_name, price, quantity)
print(f"{item_name} added to the cart.")
except ValueError as e:
print(f"Error: {e}")
elif choice == '2':
item_name = input("Enter item name to remove: ")
quantity = int(input("Enter quantity to remove: "))
try:
cart.remove_item(item_name, quantity)
print(f"{quantity} of {item_name} removed from the
cart.")
except (KeyError, ValueError) as e:
print(f"Error: {e}")
elif choice == '3':
cart.display_cart()
elif choice == '4':
new_tax_rate = get_float_input("Enter new tax rate (as a
percentage): ")
ShoppingCart.update_tax_rate(new_tax_rate / 100)
print(f"Tax rate updated to {new_tax_rate}%.")
elif choice == '5':
total = cart.calculate_total()
print(f"Total price (including tax): {total}")
elif choice == '6':
total = cart.calculate_total()
discount = get_float_input("Enter discount percentage: ")
total_after_discount = ShoppingCart.apply_discount(total,
discount)
print(f"Total after {discount}% discount:
{total_after_discount}")
elif choice == '7':
print("Exiting the shopping cart.")
del cart
break
else:
print("Invalid choice. Please select an option between 1
and 7.")
user_interaction()
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 1
Enter item name: pen
Enter item price: 10
Enter item quantity: 3
pen added to the cart.
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 1
Enter item name: ball
Enter item price: 30
Enter item quantity: 2
ball added to the cart.
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 1
Enter item name: rubber
Enter item price: 3
Enter item quantity: 4
rubber added to the cart.
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 2
Enter item name to remove: rubber
Enter quantity to remove: 2
2 of rubber removed from the cart.
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 3
Item: pen, Price: 10.0, Quantity: 3
Item: ball, Price: 30.0, Quantity: 2
Item: rubber, Price: 3.0, Quantity: 2
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 5
Total price (including tax): 100.80000000000001
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 4
Enter new tax rate (as a percentage): 3
Tax rate updated to 3.0%.
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 5
Total price (including tax): 98.88
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 6
Enter discount percentage: 2
Total after 2.0% discount: 96.9024
--- Shopping Cart Menu ---
1. Add Item
2. Remove Item
3. Display Cart
4. Update Tax Rate
5. Calculate Total
6. Apply Discount
7. Exit
Choose an option (1-7): 7
Exiting the shopping cart.
Shopping cart deleted.
Day 5 Program 3
from abc import ABC,abstractmethod
class Question(ABC):
def add_MCQ(self,Q,A):
pass
def add_SQ(self,Q,A):
pass
class Quiz(Question):
def __init__(self):
self.mcq={}
self.sq={}
self.s=0
self.t=0
def add_MCQ(self,Q,A):
self.mcq[Q]=A
def add_SQ(self,Q,A):
self.sq[Q]=A
def quiz(self):
for i in self.mcq.keys():
a=input(i)
if a==self.mcq[i]:
self.s+=1
self.t+=1
for i in self.sq.keys():
a=input(i)
if a==self.sq[i]:
self.s+=1
self.t+=1
print("SCORE:",self.s,"/",self.t)
if self.s==self.t:
print("Perfect score")
q1=Question()
q2=Quiz()
ch=0
while ch!=3:
print("1.Add questions")
print("2.Attend quiz")
print("3.Exit")
ch=int(input("Enter choice:"))
if ch==1:
print("1.MCQ")
print("2.Short questions")
ch1=int(input("Enter choice:"))
if ch1==1:
q=input("Enter question:")
a=input("Enter answer:")
q2.add_MCQ(q,a)
elif ch1==2:
q=input("Enter question:")
a=input("Enter answer:")
q2.add_SQ(q,a)
else:
print("Invalid choice")
elif ch==2:
q2.quiz()
elif ch==3:
print("Exiting")
else:
print("Invalid choice")
1.Add questions
2.Attend quiz
3.Exit
Enter choice:1
1.MCQ
2.Short questions
Enter choice:1
Enter question:Who was the first prime minister of India(Jawaharlal
Nehru, BR Ambedhkar, Mahathma Gandhi)?
Enter answer:Jawaharlal Nehru
1.Add questions
2.Attend quiz
3.Exit
Enter choice:1
1.MCQ
2.Short questions
Enter choice:1
Enter question:Which is the largest planet in the solar system(Earth,
Mars, Jupiter)?
Enter answer:Jupiter
1.Add questions
2.Attend quiz
3.Exit
Enter choice:1
1.MCQ
2.Short questions
Enter choice:2
Enter question:Which are the two official languages of India?
Enter answer:English and Hindi
1.Add questions
2.Attend quiz
3.Exit
Enter choice:1
1.MCQ
2.Short questions
Enter choice:2
Enter question:which is the largest ocean?
Enter answer:Pacific Ocean
1.Add questions
2.Attend quiz
3.Exit
Enter choice:2
Who was the first prime minister of India(Jawaharlal Nehru, BR
Ambedhkar, Mahathma Gandhi)?Jawaharlal Nehru
Which is the largest planet in the solar system(Earth, Mars, Jupiter)?
Jupiter
Which are the two official languages of India?English and Hindi
which is the largest ocean?Pacific Ocean
SCORE: 4 / 4
Perfect score
1.Add questions
2.Attend quiz
3.Exit
Enter choice:3
Exiting
Day 6 Program 1
import tkinter as tk
from tkinter import messagebox
word_dict = {
"apple": "A fruit that is typically red, green, or yellow.",
"banana": "A long, curved fruit with a yellow skin.",
"ball": "A round shapped toy or sports equipment for playing games
like soccer, cricket and others.",
"cat": "A small domesticated carnivorous mammal with soft fur.",
"dog": "A domesticated carnivorous mammal that typically has a
long snout.",
"elephant": "A large mammal with a trunk and tusks, native to
Africa and Asia."
}
username = "user1"
password = "password123"
def authenticate_user():
entered_username = username_entry.get()
entered_password = password_entry.get()
if entered_username == username and entered_password == password:
messagebox.showinfo("Authentication", "Login Successful!")
login_frame.pack_forget()
app_frame.pack()
else:
messagebox.showerror("Authentication", "Invalid username or
password.")
def get_meaning():
word = word_entry.get().lower()
if word in word_dict:
meaning_label.config(text=f"Meaning: {word_dict[word]}")
else:
meaning_label.config(text="Word not found.")
def count_words():
char = letter_entry.get().lower()
count = sum(1 for word in word_dict if word.startswith(char))
count_label.config(text=f"Words starting with '{char}': {count}")
def find_word_of_length():
try:
n = int(length_entry.get())
for word in word_dict:
if len(word) == n:
first_word_label.config(text=f"First word of length
{n}: {word}")
return
first_word_label.config(text=f"No word of length {n} found.")
except ValueError:
first_word_label.config(text="Please enter a valid number.")
root = tk.Tk()
root.title("English Dictionary")
login_frame = tk.Frame(root)
login_frame.pack(padx=10, pady=10)
tk.Label(login_frame, text="Username:").grid(row=0, column=0, padx=5,
pady=5)
username_entry = tk.Entry(login_frame)
username_entry.grid(row=0, column=1, padx=5, pady=5)
tk.Label(login_frame, text="Password:").grid(row=1, column=0, padx=5,
pady=5)
password_entry = tk.Entry(login_frame, show="*")
password_entry.grid(row=1, column=1, padx=5, pady=5)
login_button = tk.Button(login_frame, text="Login",
command=authenticate_user)
login_button.grid(row=2, columnspan=2, pady=10)
app_frame = tk.Frame(root)
tk.Label(app_frame, text="Enter a word:").grid(row=0, column=0,
padx=5, pady=5)
word_entry = tk.Entry(app_frame)
word_entry.grid(row=0, column=1, padx=5, pady=5)
meaning_button = tk.Button(app_frame, text="Get Meaning",
command=get_meaning)
meaning_button.grid(row=0, column=2, padx=5, pady=5)
meaning_label = tk.Label(app_frame, text="Meaning: ")
meaning_label.grid(row=1, columnspan=3, padx=5, pady=5)
tk.Label(app_frame, text="Enter a character:").grid(row=2, column=0,
padx=5, pady=5)
letter_entry = tk.Entry(app_frame)
letter_entry.grid(row=2, column=1, padx=5, pady=5)
count_button = tk.Button(app_frame, text="Count Words",
command=count_words)
count_button.grid(row=2, column=2, padx=5, pady=5)
count_label = tk.Label(app_frame, text="Words starting with: ")
count_label.grid(row=3, columnspan=3, padx=5, pady=5)
tk.Label(app_frame, text="Enter word length (n):").grid(row=4,
column=0, padx=5, pady=5)
length_entry = tk.Entry(app_frame)
length_entry.grid(row=4, column=1, padx=5, pady=5)
length_button = tk.Button(app_frame, text="Find Word",
command=find_word_of_length)
length_button.grid(row=4, column=2, padx=5, pady=5)
first_word_label = tk.Label(app_frame, text="First word of given
length: ")
first_word_label.grid(row=5, columnspan=3, padx=5, pady=5)
root.mainloop()
Day 7 Program 1
import pandas as pd
df=pd.read_csv("titanic.csv")
print("List of passengers in Titanic")
print(df)
print("Number of males : ",df["Sex"].value_counts())
print("List of female passengers : ")
print(df[df["Sex"]=="female"])
survived=0
for i in df["Survived"]:
if(i==1):
survived+=1
print("Number odf people who survived : ",survived)
print("\nfirst 10 rows of dataset :\n",df.head(10))
print("\nColumns in dataset :\n ",df.columns)
print("\nDatatypes of each columns : \n",df.dtypes)
print("\nNumber of missing values in each column :\
n",df.isnull().sum())
print("\nMean of age : ",df["Age"].mean())
print("\nMedian of age : ",df["Age"].median())
print("\nStandard deviation of age : ",df["Age"].std())
print("\nMinimum fare payed by passenger : ",df["Fare"].min())
print("\nMaximum fare payed by passenger : ",df["Fare"].max())
print("\nThe number of unique values in each column : \
n",df.nunique())
print("\nSurvival rate of passengers in each passenger class
(Pclass) : ",df.groupby("Pclass")["Survived"].mean() * 100)
print("\nAverage fare for each class (Pclass) : ",df.groupby("Pclass")
["Fare"].mean())
print("\nThe details of passengers who paid more than $200 for a
ticket :\n",df[df["Fare"]>200])
print("\nNumber of passengers boarded at each embarkation point
(Embarked column) : \n",df["Embarked"].value_counts())
List of passengers in Titanic
PassengerId Survived Pclass \
0 1 0 3
1 3 1 3
2 4 1 1
3 5 0 3
4 7 0 1
.. ... ... ...
886 876 1 3
887 880 1 1
888 890 1 1
889 62 1 1
890 830 1 1
Name Sex Age
Fare \
0 Braund, Mr. Owen Harris male 22.0
7.2500
1 Heikkinen, Miss. Laina female 26.0
7.9250
2 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0
53.1000
3 Allen, Mr. William Henry male 35.0
8.0500
4 McCarthy, Mr. Timothy J male 54.0
51.8625
.. ... ... ...
...
886 Najib, Miss. Adele Kiamie "Jane" female 15.0
7.2250
887 Potter, Mrs. Thomas Jr (Lily Alexenia Wilson) female 56.0
83.1583
888 Behr, Mr. Karl Howell male 26.0
30.0000
889 Icard, Miss. Amelie female 38.0
80.0000
890 Stone, Mrs. George Nelson (Martha Evelyn) female 62.0
80.0000
Cabin Embarked
0 NaN S
1 NaN S
2 C123 S
3 NaN S
4 E46 S
.. ... ...
886 NaN C
887 C50 C
888 C148 C
889 B28 C
890 B28 C
[891 rows x 9 columns]
Number of males : male 577
female 314
Name: Sex, dtype: int64
List of female passengers :
PassengerId Survived Pclass \
1 3 1 3
2 4 1 1
6 9 1 3
7 11 1 3
8 12 1 1
.. ... ... ...
885 875 1 2
886 876 1 3
887 880 1 1
889 62 1 1
890 830 1 1
Name Sex Age
Fare \
1 Heikkinen, Miss. Laina female 26.0
7.9250
2 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0
53.1000
6 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0
11.1333
7 Sandstrom, Miss. Marguerite Rut female 4.0
16.7000
8 Bonnell, Miss. Elizabeth female 58.0
26.5500
.. ... ... ...
...
885 Abelson, Mrs. Samuel (Hannah Wizosky) female 28.0
24.0000
886 Najib, Miss. Adele Kiamie "Jane" female 15.0
7.2250
887 Potter, Mrs. Thomas Jr (Lily Alexenia Wilson) female 56.0
83.1583
889 Icard, Miss. Amelie female 38.0
80.0000
890 Stone, Mrs. George Nelson (Martha Evelyn) female 62.0
80.0000
Cabin Embarked
1 NaN S
2 C123 S
6 NaN S
7 G6 S
8 C103 S
.. ... ...
885 NaN C
886 NaN C
887 C50 C
889 B28 C
890 B28 C
[314 rows x 9 columns]
Number odf people who survived : 342
first 10 rows of dataset :
PassengerId Survived Pclass \
0 1 0 3
1 3 1 3
2 4 1 1
3 5 0 3
4 7 0 1
5 8 0 3
6 9 1 3
7 11 1 3
8 12 1 1
9 13 0 3
Name Sex Age
Fare \
0 Braund, Mr. Owen Harris male 22.0
7.2500
1 Heikkinen, Miss. Laina female 26.0
7.9250
2 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0
53.1000
3 Allen, Mr. William Henry male 35.0
8.0500
4 McCarthy, Mr. Timothy J male 54.0
51.8625
5 Palsson, Master. Gosta Leonard male 2.0
21.0750
6 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0
11.1333
7 Sandstrom, Miss. Marguerite Rut female 4.0
16.7000
8 Bonnell, Miss. Elizabeth female 58.0
26.5500
9 Saundercock, Mr. William Henry male 20.0
8.0500
Cabin Embarked
0 NaN S
1 NaN S
2 C123 S
3 NaN S
4 E46 S
5 NaN S
6 NaN S
7 G6 S
8 C103 S
9 NaN S
Columns in dataset :
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age',
'Fare',
'Cabin', 'Embarked'],
dtype='object')
Datatypes of each columns :
PassengerId int64
Survived int64
Pclass int64
Name object
Sex object
Age float64
Fare float64
Cabin object
Embarked object
dtype: object
Number of missing values in each column :
PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 177
Fare 0
Cabin 687
Embarked 0
dtype: int64
Mean of age : 29.69911764705882
Median of age : 28.0
Standard deviation of age : 14.526497332334042
Minimum fare payed by passenger : 0.0
Maximum fare payed by passenger : 512.3292
The number of unique values in each column :
PassengerId 891
Survived 2
Pclass 3
Name 891
Sex 2
Age 88
Fare 248
Cabin 147
Embarked 3
dtype: int64
Survival rate of passengers in each passenger class (Pclass) : Pclass
1 62.962963
2 47.282609
3 24.236253
Name: Survived, dtype: float64
Average fare for each class (Pclass) : Pclass
1 84.154687
2 20.662183
3 13.675550
Name: Fare, dtype: float64
The details of passengers who paid more than $200 for a ticket :
PassengerId Survived Pclass \
20 28 0 1
59 89 1 1
242 342 1 1
313 439 0 1
379 528 0 1
495 690 1 1
524 731 1 1
562 780 1 1
744 119 0 1
767 259 1 1
774 300 1 1
780 312 1 1
795 378 0 1
797 381 1 1
828 558 0 1
849 680 1 1
855 701 1 1
859 717 1 1
861 738 1 1
862 743 1 1
Name Sex
Age \
20 Fortune, Mr. Charles Alexander male 19.0
59 Fortune, Miss. Mabel Helen female 23.0
242 Fortune, Miss. Alice Elizabeth female 24.0
313 Fortune, Mr. Mark male 64.0
379 Farthing, Mr. John male NaN
495 Madill, Miss. Georgette Alexandra female 15.0
524 Allen, Miss. Elisabeth Walton female 29.0
562 Robert, Mrs. Edward Scott (Elisabeth Walton Mc... female 43.0
744 Baxter, Mr. Quigg Edmond male 24.0
767 Ward, Miss. Anna female 35.0
774 Baxter, Mrs. James (Helene DeLaudeniere Chaput) female 50.0
780 Ryerson, Miss. Emily Borie female 18.0
795 Widener, Mr. Harry Elkins male 27.0
797 Bidois, Miss. Rosalie female 42.0
828 Robbins, Mr. Victor male NaN
849 Cardeza, Mr. Thomas Drake Martinez male 36.0
855 Astor, Mrs. John Jacob (Madeleine Talmadge Force) female 18.0
859 Endres, Miss. Caroline Louise female 38.0
861 Lesurer, Mr. Gustave J male 35.0
862 Ryerson, Miss. Susan Parker "Suzette" female 21.0
Fare Cabin Embarked
20 263.0000 C23 C25 C27 S
59 263.0000 C23 C25 C27 S
242 263.0000 C23 C25 C27 S
313 263.0000 C23 C25 C27 S
379 221.7792 C95 S
495 211.3375 B5 S
524 211.3375 B5 S
562 211.3375 B3 S
744 247.5208 B58 B60 C
767 512.3292 NaN C
774 247.5208 B58 B60 C
780 262.3750 B57 B59 B63 B66 C
795 211.5000 C82 C
797 227.5250 NaN C
828 227.5250 NaN C
849 512.3292 B51 B53 B55 C
855 227.5250 C62 C64 C
859 227.5250 C45 C
861 512.3292 B101 C
862 262.3750 B57 B59 B63 B66 C
Number of passengers boarded at each embarkation point (Embarked
column) :
S 644
C 170
Q 77
Name: Embarked, dtype: int64
Day 8 Program 1
import pandas as pd
import matplotlib.pyplot as plt
print("--1. Load the Data:--")
df = pd.read_csv("sales_data.csv")
print(df)
print("--2. Data Cleaning:--")
df["Quantity"] = df["Quantity"].fillna(value=df["Quantity"].median())
df["Price"] = df["Price"].fillna(value=df["Price"].median())
print(df)
print("--3. Sales Analysis--")
df["Total_Sales"] = df["Quantity"] * df["Price"]
print("\nTotal sales for each region:\n", df.groupby("Region")
["Total_Sales"].sum())
print("\nThe top 3 product categories with the highest sales:\n",
df.groupby("Category")["Total_Sales"].sum().nlargest(3))
df["OrderDate"] = pd.to_datetime(df["OrderDate"], dayfirst=True)
def plot_sales_visualizations():
sales_per_region = df.groupby("Region")["Total_Sales"].sum()
plt.figure(figsize=(10, 5))
sales_per_region.plot(kind="bar", color="skyblue",
edgecolor="black")
plt.title("Total Sales per Region")
plt.xlabel("Region")
plt.ylabel("Total Sales")
plt.xticks(rotation=45)
plt.grid(axis="y", linestyle="--", alpha=0.7)
plt.show()
# Line Chart: Monthly Sales Trends
df["Month"] = df["OrderDate"].dt.to_period("M")
monthly_sales = df.groupby("Month")["Total_Sales"].sum()
plt.figure(figsize=(10, 5))
monthly_sales.plot(kind="line", marker="o", color="green",
linestyle="-", linewidth=2, markersize=6)
plt.title("Monthly Sales Trends")
plt.xlabel("Month")
plt.ylabel("Total Sales")
plt.xticks(rotation=45)
plt.grid(True, linestyle="--", alpha=0.7)
plt.show()
print("--5. Visualization--")
plot_sales_visualizations()
print("--6. Export Results--")
df.to_csv("sales_analysis.csv", index=False)
print("Sales analysis saved successfully.")
--1. Load the Data:--
OrderID Product Category Region Quantity Price
OrderDate
0 1 Headphones Electronics South 1.0 1727.69 02-
11-2024
1 2 Smartphone Electronics North 1.0 654.63 08-
09-2024
2 3 Smartphone Electronics South 8.0 1944.04 01-
03-2025
3 4 Chair Furniture West 2.0 637.80 26-
07-2024
4 5 Jeans Clothing West 10.0 1133.12 04-
11-2024
... ... ... ... ... ... ...
...
4995 4996 Table Furniture South 10.0 897.25 17-
12-2024
4996 4997 Sweater Clothing South 2.0 649.84 16-
12-2024
4997 4998 Smartphone Electronics East 8.0 219.28 16-
09-2024
4998 4999 Laptop Electronics South 8.0 1429.66 11-
01-2025
4999 5000 Headphones Electronics West 2.0 1895.67 14-
04-2024
[5000 rows x 7 columns]
--2. Data Cleaning:--
OrderID Product Category Region Quantity Price
OrderDate
0 1 Headphones Electronics South 1.0 1727.69 02-
11-2024
1 2 Smartphone Electronics North 1.0 654.63 08-
09-2024
2 3 Smartphone Electronics South 8.0 1944.04 01-
03-2025
3 4 Chair Furniture West 2.0 637.80 26-
07-2024
4 5 Jeans Clothing West 10.0 1133.12 04-
11-2024
... ... ... ... ... ... ...
...
4995 4996 Table Furniture South 10.0 897.25 17-
12-2024
4996 4997 Sweater Clothing South 2.0 649.84 16-
12-2024
4997 4998 Smartphone Electronics East 8.0 219.28 16-
09-2024
4998 4999 Laptop Electronics South 8.0 1429.66 11-
01-2025
4999 5000 Headphones Electronics West 2.0 1895.67 14-
04-2024
[5000 rows x 7 columns]
--3. Sales Analysis--
Total sales for each region:
Region
East 6812147.09
North 6769764.93
South 7208919.91
West 7001614.67
Name: Total_Sales, dtype: float64
The top 3 product categories with the highest sales:
Category
Electronics 11012055.01
Furniture 8482649.38
Clothing 8297742.21
Name: Total_Sales, dtype: float64
--5. Visualization--
--6. Export Results--
Sales analysis saved successfully.