Untitled

 avatar
unknown
plain_text
2 years ago
14 kB
8
Indexable
class BankAccount():
    def __init__(self,name,acc_no,pin,mobile_no,balance):
        self.name=name
        self.acc_no=acc_no
        self.pin = pin
        self.mobile_no = mobile_no
        self.balance = balance

class BankingSysytem():

    def __init__(self):
        self.details={}

    def insert_account(self,name,acc_no,pin,mobile_no,balance):
        if acc_no in self.details:
            print("account already exits")
        else:
            account=BankAccount(name,acc_no,pin,mobile_no,balance)
            self.details[acc_no]=account
            print("account created successfully")
    
    def deposit(self,acc_no):
        if acc_no in self.details:
            amount=float(input("enter amount:"))
            if amount<0:
                print("invalid amount ")
            else:
                self.details[acc_no].balance+=amount
                print("balance:",self.details[acc_no].balance)
                print("amount deposited successfully!!")
        else:
            print("invalid account number")
            
    def withdraw(self,acc_no):
        if acc_no in self.details:
            amount=float(input("enter the amount:"))
            if amount>self.details[acc_no].balance:
                print("insufficient balance")
            elif amount<0:
                print("invalid amount")
            else:
                self.details[acc_no].balance-=amount
                print("balance:",self.details[acc_no].balance)
                print("amount withdrawn successfully")
    
    def authentication(self,acc_no,pin):
        if acc_no in self.details:
            if pin ==self.details[acc_no].pin:
                print("authentication done")
            else:
                print("incorrect pin")
        else:
            print("invalid account number")

    def display(self,acc_no):
        if acc_no in self.details:
            account=self.details[acc_no]
            print(f"name:{account.name}")
            print(f"account number:{account.acc_no}")
            print(f"mobile number:{account.mobile_no}")
            print(f"balance:{account.balance}")
        else:
            print("invalid account number ")

if __name__=='__main__':
    bank=BankingSysytem()
    
    while True:
        print("WELCOME!")
        print("1. Create account")
        print("2. Authenticate")
        print("3. Deposit")
        print("4. Withdraw")
        print("5. Display account details")
        print("6. Exit")
        ch = int(input("Enter your choice: "))
        if ch== 1:
            name=str(input("enter your name:"))
            acc_no=int(input("enter your acc number:"))
            mobile_no=input("enter your number: ")
            pin=input("enter your pin:")
            balance=float(input("enter your balance :"))
            bank.insert_account(name,acc_no,pin,mobile_no,balance)
        elif ch==2:
            acc_no=int(input("enter your acc number:"))
            pin=int(input("enter the pin :"))
            bank.authentication(acc_no,pin)
        elif ch==3:
            acc_no=int(input("enter your acc number:"))
            bank.deposit(acc_no)
        elif ch==4:
            acc_no=int(input("enter your acc number:"))
            bank.withdraw(acc_no)
        elif ch==5:
            acc_no=int(input("enter your acc number:"))
            bank.display(acc_no)
        elif ch==6:
            acc_no=int(input("enter your acc number:"))
            print("exited..")
            break
        else:
            print("invalid option")

            -----------------------------------------
class Book(): 
    def __init__(self,title,author,isbn,available_copies,total_copies): 
        self.title=title 
        self.author=author 
        self.isbn=isbn 
        self.available_copies=available_copies 
        self.total_copies=total_copies 
    def display1(self): 
        print("\ntitle:",self.title) 
        print("author:",self.author) 
        print("ISBN code:",self.isbn) 
        print("available copies of the book :",self.available_copies) 
        print("total no.of copies of the book:", self.total_copies) 
    def checkout(self): 
        self.available_copies -=1 
        print("the available copies of the book is",self.available_copies) 
    def return_book(self): 
        self.available_copies +=1 
        print("the available copies of the book is",self.available_copies) 
 
class Library(object): 
    books = [] 
    Author = [] 
    Title=[] 
     
    def __init__(self, sub, author, isbn,title): 
        self.sub = sub 
        self.author = author 
        self.isbn = isbn 
        self.title = title 
    def add_book(self): 
        Library.books.append((self.sub,self.author,self.isbn,self.title)) 
    def search_isbn(self,isbn): 
        for book in Library.books: 
            if book[2]==isbn: 
                return book 
    def search_author(self,author): 
        for book in Library.books: 
            if book[1]==author: 
                Library.Author.append(book) 
        return Library.Author 
     
class User: 
    def __init__(self, name, lib_no): 
        self.name = name 
        self.lib_no = lib_no 
        self.checked_out_books = [] 
    def checkout_book(self, book_title): 
        if book_title not in self.checked_out_books: 
            self.checked_out_books.append(book_title) 
            print(f"{self.name} has checked out '{book_title}'") 
        else: 
            print(f"{self.name} already has '{book_title}' checked out.") 
    def return_book(self, book_title): 
        if book_title in self.checked_out_books: 
            self.checked_out_books.remove(book_title) 
            print(f"{self.name} has returned '{book_title}'") 
        else: 
            print(f"{self.name} didnt return the book '{book_title}'.") 
 
book_1=Book("c programming","local author",'12345678',31,11) 
book_1.checkout() 
book_1.display1() 
print("\n")  
 
book = Library("python", 'foreign author', '12345', 22) 
book.add_book() 
book = Library('Maths', 'saravanan', '1111111', 5) 
book.add_book() 
book = Library('java', 'local author', '0000000', 11) 
book.add_book() 
 
print (book.search_isbn('12345')) 
print (book.search_author('saravanan')) 
print("\n") 
user1 = User("nathish", "103") 
user1.checkout_book("python") 
user1.checkout_book("java") 
user1.return_book("c programming")
--------------------------------------------------------------------------------------------------
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
from PIL import Image, ImageOps
print("DISPLAY IMAGE")
im = Image.open("c:/dog/image.jpg")
plt.imshow(im)
plt.show()
print("PIXEL VALUES")
img = np.array(im)
print(img)
print("DIMENSION")
print('# of dims: ',img.ndim)
print('img shape: ',img.shape)
print('dtype: ',img.dtype)
print(type(img))
print("PIXEL VALUE AT [R, G, B]")
print(img[20, 20])
img_R = img[:, :, 0] # Index 0 for the Red channel
img_G = img[:, :, 1] # Index 1 for the Green channel
img_B = img[:, :, 2] # Index 2 for the Blue channel
plt.imshow(img_B)
plt.title('Red Channel')
plt.axis('off') 
plt.show()
img_R, img_G, img_B = img.copy(), img.copy(), img.copy()
img_R[:, :, (1, 2)] = 0
img_G[:, :, (0, 2)] = 0
img_B[:, :, (0, 1)] = 0
img_rgb = np.concatenate((img_R,img_G,img_B),axis=1)
plt.figure(figsize=(15, 15))
plt.axis('off')
plt.imshow(img_rgb)
plt.show()
img_0 = (img // 64) * 64
img_1 = (img // 128) * 128
img_all = np.concatenate((img, img_0, img_1), axis=1)
plt.figure(figsize=(15, 15))
plt.imshow(img_all)
plt.show()
fig = plt.figure(figsize=(10, 10))
ax1 = fig.add_subplot(1, 2, 1)
ax1.imshow(img)
ax1.set_title('Original')
top_margin = 20
bottom_margin = 30
left_margin = 10
right_margin = 15
img0 = img[top_margin:-bottom_margin, left_margin:-right_margin, :]
if img0.shape[0] > 0 and img0.shape[1] > 0:
    # Display the trimmed image
    ax2 = fig.add_subplot(1, 2, 2)
    ax2.imshow(img0)
    ax2.set_title('Trimmed')
    plt.show()
else:
    print("Trimmed image has zero dimensions.")
plt.imshow(img0)
plt.title("rotated")
plt.imshow(np.rot90(im))
img = 255 - img
fig = plt.figure(figsize=(10, 10))
plt.imshow(img)
plt.title('Negative of RGB image')
plt.show()
img0 = np.array(Image.open('c:/dog/image.jpg').resize(img.shape[1::-1])) 
print(img.dtype)
dst = (img * 0.6 + img0 * 0.4).astype(np.uint8)   # Blending them in
plt.figure(figsize=(10, 10))
plt.imshow(dst)
plt.show()
-----------------------------------------------------------------
import pandas as pd
import numpy as np
import xml.etree.ElementTree as et
score = {'Rohit Sharma': [120,135,115,140],
 'Virat Kohli': [180,170,140,150],
 'Dhoni': [143,136,129,152],
 'Shubman Gil': [90,100,138,128],
 'K L Rahul': [153,142,131,164]}
df = pd.DataFrame(score, index=['Test1', 'Test2', 'Test3', 'Test4'])
print("DATAFRAME:\n")
print(df)
a=df.to_html()
print("HTML CODE:\n")
print(a)
print("MODIFIED DATA:\n")
df.style.set_properties(**{'background-color': 'yellow', 'color': 'red'})

-----------------------------------------------------------------------------------
import pandas as pd
a={"Name":['Michael','Uma','Alice','Priya'],"Year":[2,3,1,4],"Section":['A','B','A','C'],"Gender":['M','F','M','F'],"Cutoff":[189.9,175.4,190.1,182.5]}
df=pd.DataFrame(a)
print(“DATAFRAME”)
print(df)
x=df.to_xml("c:/app/students.xml")
import xml.etree.ElementTree as et 

xtree = et.parse("c:/app/students.xml")
xroot = xtree.getroot() 

df_cols = ["Name", "Year", "Section", "Gender","Cutoff"]
rows = []

for node in xroot: 
    s_name = node.find("Name").text
    s_year = node.find("Year").text 
    s_section = node.find("Section").text 
    s_gender = node.find("Gender").text 
    s_cutoff = node.find("Cutoff").text 
    rows.append({"Name": s_name, "Year": s_year, 
                 "Section": s_section, "Gender": s_gender,"Cutoff": s_cutoff})

out_df = pd.DataFrame(rows, columns = df_cols)
print(“AFTER READING FROM XML”)
print(out_df)

---------------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt

data = {'year': [2017, 2018, 2019, 2020],
        'maxtemp': [32, 33, 35, 34],
        'mintemp': [20, 22, 21, 23],
        'rainfall': [123, 140, 135, 160]}
df = pd.DataFrame(data)
print(df)
ax = df.plot(kind='bar', x='year', y=['maxtemp', 'mintemp', 'rainfall'], title='Temperature', legend=True, fontsize=12)
ax.set_xlabel('Year', fontsize=12)
ax.set_ylabel('Temperature', fontsize=12)
x_labels = ['2017', '2018', '2019', '2020']
plt.show()
----------------------------------------------------------------------------

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("C://Users//madha//Downloads//ABC_Sales.xlsx")
print(df)
ax= df.loc[:, 'facecream':'moisturizer'].plot(kind='line', title='salesdata', figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel('month', fontsize=12)
ax.set_ylabel('sales', fontsize=12)
plt.show()
ax = df.plot(kind='scatter', x='total_units', y='total_profit', title='Sales Data', legend=True, fontsize=12)
ax.set_xlabel('totalunits', fontsize=12)
ax.set_ylabel('totalprofit', fontsize=12)
plt.show()


-----------------------------------------------------------------------------------

import numpy as np
import pandas as pd
df = pd.read_csv('Dummy_Sales_Data_v1.csv')
df1 = pd.read_csv('Dummy_Sales_Data_v1.csv')
df
# Display the first 7 rows
first_7_rows = df.head(7)
print("First 7 rows:")
first_7_rows#
# Display the last 5 rows
last_5_rows = df.tail(5)
print("\nLast 5 rows:")
last_5_rows
# Display the row randomly.
random_rows = df1.sample(frac=1)
print("Randomly shuffled rows:")
random_rows
# Display information about the DataFrame
print("DataFrame Information:")
df.info()
# Display the descriptive statistics about the data.
data_statistics = df.describe()
print("Descriptive Statistics:")
print(data_statistics)
# Select a Subset of the Dataset
subset = df.iloc[2:6, 1:3]
subset
# Display the group of rows and columns identified by their labels/names and uses row and column numbers
data = df1.loc[[0,1,2], ['OrderID',"Quantity",'UnitPrice(USD)']]
data
# Display unique values and number of unique records.
for column in df.columns:
 unique_values = df[column].unique()
 num_unique = df[column].nunique()
 print(f"Unique Values in {column}:", unique_values)
 print(f"Number of Unique Records in {column}:", num_unique)
# Display the rows and columns which have null values. And display the missing feature (Example: Product
category). Also replace the missing values.
null_values = df1[df.isnull().any(axis=1)]
print("Rows with Null Values:")
null_values
null_columns = df.columns[df.isnull().any()]
print("\nColumns with Null Values:")
print(null_columns)
missing_features = df.columns[df.isnull().any()].tolist()
print("\nMissing Features:")
print(missing_features)
data2= df.fillna(0)
data2
# Sort the DataFrame in Ascending and descending order.
ascending_df = df.sort_values(by='UnitPrice(USD)')
print("\nDataFrame sorted in Ascending Order:")
ascending_df
descending_df = df.sort_values(by='UnitPrice(USD)', ascending=False)
print("\nDataFrame sorted in Descending Order:")
descending_df
# Display the relationship among all the columns.
data1 = {'OrderID':pd.Series(df1['OrderID']).tolist(),
 'Quantity':pd.Series(df1['Quantity']).tolist(),
 'UnitPrice(USD)':pd.Series(df1['UnitPrice(USD)']).tolist(),
 'Shipping_Cost(USD)':pd.Series(df1['Shipping_Cost(USD)']).tolist(),
 'Delivery_Time(Days)': pd.Series(df1['Delivery_Time(Days)']).tolist(),
 'OrderCode': pd.Series(df1['OrderCode']).tolist()}
df2 = pd.DataFrame(data1)
corr1= df2.corr()
corr1


-----------------------------------------
import random
import datetime
def generate_token():
    return random.randint(1000,9999)
def perform_transaction(acc_no,trans_type,amount):
    token=generate_token()
    timestamp=datetime.datetime.now()
    print(f"token number:{token}")
    print(f"account number:{acc_no}")
    print(f"transaction type:{trans_type}")
    print(f"amount:{amount}")
    print(f"date and time:{timestamp}")
    
acc_no="12345"
trans_type="withdrawl"
amount="500"
perform_transaction(acc_no,trans_type,amount)
Editor is loading...
Leave a Comment