Bank Managing 1.0

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Import csv

Import random

Import os

# Constants

DATABASE_FILE = “bank_accounts.csv”

ADMIN_PASSWORD = “admin123”

# Initialize the database if it doesn’t exist

Def initialize_database():

If not os.path.exists(DATABASE_FILE):

With open(DATABASE_FILE, mode=’w’, newline=’’) as file:

Writer = csv.writer(file)

Writer.writerow([“Username”, “AccountNumber”, “Password”,


“Balance”, “IsAdmin”, “Loan”])

# Generate a unique 10-digit account number

Def generate_account_number():

Return str(random.randint(10**9, 10**10 – 1))

# Function to create a new account

Def create_account():

Print(“\n--- Create Account ---“)

Username = input(“Enter your username: “).strip()


Password = input(“Enter your password: “).strip()

Is_admin = input(“Are you an admin? (yes/no): “).strip().lower() == “yes”

While True:

Try:

Initial_deposit = float(input(“Enter initial deposit amount: “))

If initial_deposit < 0:

Raise ValueError(“Deposit must be non-negative.”)

Break

Except ValueError as e:

Print(f”Invalid input: {e}”)

Account_number = generate_account_number()

With open(DATABASE_FILE, mode=’a’, newline=’’) as file:

Writer = csv.writer(file)

Writer.writerow([username, account_number, password, initial_deposit,


is_admin])

Print(f”Account created successfully! Your account number is


{account_number}”)

# Function to deposit money into an account

Def deposit():

Print(“\n--- Deposit ---“)

Account_number = input(“Enter your account number: “).strip()

While True:
Try:

Amount = float(input(“Enter the amount to deposit: “))

If amount <= 0:

Raise ValueError(“Amount must be positive.”)

Break

Except ValueError as e:

Print(f”Invalid input: {e}”)

Accounts = load_accounts()

For account in accounts:

If account[‘AccountNumber’] == account_number:

Account[‘Balance’] = str(float(account[‘Balance’]) + amount)

Save_accounts(accounts)

Print(“Deposit successful!”)

Return

Print(“Account not found.”)

# Function to withdraw money from an account

Def withdraw():

Print(“\n--- Withdraw ---“)

Account_number = input(“Enter your account number: “).strip()

Password = input(“Enter your password: “).strip()

While True:

Try:

Amount = float(input(“Enter the amount to withdraw: “))


If amount <= 0:

Raise ValueError(“Amount must be positive.”)

Break

Except ValueError as e:

Print(f”Invalid input: {e}”)

Accounts = load_accounts()

For account in accounts:

If account[‘AccountNumber’] == account_number and


account[‘Password’] == password:

If float(account[‘Balance’]) >= amount:

Account[‘Balance’] = str(float(account[‘Balance’]) – amount)

Save_accounts(accounts)

Print(“Withdrawal successful!”)

Return

Else:

Print(“Insufficient balance.”)

Return

Print(“Invalid account number or password.”)

# Function to transfer money between accounts

Def transfer():

Print(“\n--- Transfer ---“)

From_account = input(“Enter your account number: “).strip()

Password = input(“Enter your password: “).strip()


To_account = input(“Enter the recipient’s account number: “).strip()

While True:

Try:

Amount = float(input(“Enter the amount to transfer: “))

If amount <= 0:

Raise ValueError(“Amount must be positive.”)

Break

Except ValueError as e:

Print(f”Invalid input: {e}”)

Accounts = load_accounts()

From_account_data = None

To_account_data = None

For account in accounts:

If account[‘AccountNumber’] == from_account and account[‘Password’]


== password:

From_account_data = account

If account[‘AccountNumber’] == to_account:

To_account_data = account

If from_account_data and to_account_data:

If float(from_account_data[‘Balance’]) >= amount:

From_account_data[‘Balance’] =
str(float(from_account_data[‘Balance’]) – amount)

To_account_data[‘Balance’] = str(float(to_account_data[‘Balance’]) +
amount)

Save_accounts(accounts)
Print(“Transfer successful!”)

Else:

Print(“Insufficient balance.”)

Else:

Print(“Invalid account details.”)

# Function to update account details

Def update_account():

Print(“\n--- Update Account Details ---“)

Account_number = input(“Enter your account number: “).strip()

Password = input(“Enter your current password: “).strip()

Accounts = load_accounts()

Account_found = False

For account in accounts:

If account[‘AccountNumber’] == account_number and


account[‘Password’] == password:

Account_found = True

Print(“\nWhat would you like to update?”)

Print(“1. Username”)

Print(“2. Password”)

Choice = input(“Choose an option (1/2): “).strip()

If choice == ‘1’:

New_username = input(“Enter your new username: “).strip()

Account[‘Username’] = new_username
Print(“Username updated successfully!”)

Elif choice == ‘2’:

New_password = input(“Enter your new password: “).strip()

Account[‘Password’] = new_password

Print(“Password updated successfully!”)

Else:

Print(“Invalid choice. No changes made.”)

Save_accounts(accounts)

Break

If not account_found:

Print(“Invalid account number or password.”)

# Function to apply for a loan

Def apply_for_loan():

Print(“\n--- Apply for Loan ---“)

Account_number = input(“Enter your account number: “).strip()

Password = input(“Enter your password: “).strip()

Accounts = load_accounts()

For account in accounts:

If account[‘AccountNumber’] == account_number and


account[‘Password’] == password:

Print(“\nLoan Eligibility:”)

Print(“1. Minimum account balance must be $500.”)

Print(“2. Loan amount cannot exceed 10 times your current


balance.”)

Print(“3. Maximum loan amount: $50,000.”)


Current_balance = float(account[‘Balance’])

If current_balance < 500:

Print(“You are not eligible for a loan. Minimum balance requirement


not met.”)

Return

While True:

Try:

Loan_amount = float(input(“Enter the loan amount you want to


apply for: “))

If loan_amount <= 0:

Raise ValueError(“Loan amount must be positive.”)

If loan_amount > 10 * current_balance:

Print(f”Loan amount cannot exceed 10 times your current


balance (${current_balance * 10:.2f}).”)

Elif loan_amount > 50000:

Print(“Maximum loan amount allowed is $50,000.”)

Else:

# Add loan amount to user’s balance

Account[‘Balance’] = str(current_balance + loan_amount)

Account[‘Loan’] = str(loan_amount) # Track the loan amount

Save_accounts(accounts)

Print(f”Loan of ${loan_amount:.2f} approved successfully!”)

Print(f”Your new balance is: ${float(account[‘Balance’]):.2f}”)

Return

Except ValueError as e:
Print(f”Invalid input: {e}”)

Print(“Invalid account number or password.”)

# Function to repay a loan

Def repay_loan():

Print(“\n--- Repay Loan ---“)

Account_number = input(“Enter your account number: “).strip()

Password = input(“Enter your password: “).strip()

Accounts = load_accounts()

For account in accounts:

If account[‘AccountNumber’] == account_number and


account[‘Password’] == password:

Loan_amount = float(account.get(‘Loan’, 0))

If loan_amount <= 0:

Print(“You don’t have any outstanding loans.”)

Return

Print(f”Your outstanding loan amount is: ${loan_amount:.2f}”)

While True:

Try:

Repay_amount = float(input(“Enter the amount you want to


repay: “))

If repay_amount <= 0:

Raise ValueError(“Repayment amount must be positive.”)

If repay_amount > loan_amount:

Print(f”You cannot repay more than the outstanding loan: $


{loan_amount:.2f}.”)

Else:
Loan_amount -= repay_amount

Account[‘Loan’] = str(loan_amount)

Account[‘Balance’] = str(float(account[‘Balance’]) –
repay_amount)

Save_accounts(accounts)

Print(f”Loan repayment successful! Outstanding loan: $


{loan_amount:.2f}”)

Return

Except ValueError as e:

Print(f”Invalid input: {e}”)

Print(“Invalid account number or password.”)

# Function to show account details for the current user

Def show_my_account():

Print(“\n--- Show My Account Details ---“)

Account_number = input(“Enter your account number: “).strip()

Password = input(“Enter your password: “).strip()

Accounts = load_accounts()

For account in accounts:

If account[‘AccountNumber’] == account_number and


account[‘Password’] == password:

Print(“\n--- Account Details ---“)

Print(f”Username: {account[‘Username’]}”)

Print(f”Account Number: {account[‘AccountNumber’]}”)

Print(f”Balance: {account[‘Balance’]}”)

Print(f”Is Admin: {account[‘IsAdmin’]}”)

Return
Print(“Invalid account number or password.”)

# Function to show all accounts (admin only)

Def show_all_accounts():

Print(“\n--- Show All Accounts ---“)

Admin_password = input(“Enter admin password: “).strip()

If admin_password != ADMIN_PASSWORD:

Print(“Invalid admin password.”)

Return

Accounts = load_accounts()

Print(f”{‘Username’:<20}{‘AccountNumber’:<15}{‘Balance’:<10}
{‘IsAdmin’:<8}”)

Print(“-“ * 60)

For account in accounts:

Print(f”{account[‘Username’]:<20}{account[‘AccountNumber’]:<15}
{account[‘Balance’]:<10}{account[‘IsAdmin’]:<8}”)

# Function to delete an account

Def delete_account():

Print(“\n--- Delete Account ---“)

Admin_password = input(“Enter admin password: “).strip()

If admin_password != ADMIN_PASSWORD:

Print(“Invalid admin password.”)

Return
Account_number = input(“Enter the account number to delete: “).strip()

Accounts = load_accounts()

Accounts = [account for account in accounts if


account[‘AccountNumber’] != account_number]

Save_accounts(accounts)

Print(“Account deleted successfully.”)

# Helper function to load accounts from the database

Def load_accounts():

With open(DATABASE_FILE, mode=’r’) as file:

Reader = csv.DictReader(file)

Return list(reader)

# Helper function to save accounts to the database

Def save_accounts(accounts):

With open(DATABASE_FILE, mode=’w’, newline=’’) as file:

Writer = csv.DictWriter(file, fieldnames=[“Username”,


“AccountNumber”, “Password”, “Balance”, “IsAdmin”, “Loan”])

Writer.writeheader()

Writer.writerows(accounts)

# Main menu function


Def main_menu():

Initialize_database()

While True:

Print(“\n--- Bank Management System ---“)

Print(“1. Create Account”)

Print(“2. Deposit”)

Print(“3. Withdraw”)

Print(“4. Transfer”)

Print(“5. Update Account Details”)

Print(“6. Apply for Loan”)

Print(“7. Repay Loan”)

Print(“8. Show My Account Details”)

Print(“9. Show All Accounts (Admin Only)”)

Print(“10. Delete Account (Admin Only)”)

Print(“11. Exit”)

Choice = input(“Choose an option: “).strip()

If choice == ‘1’:

Create_account()

Elif choice == ‘2’:

Deposit()

Elif choice == ‘3’:

Withdraw()

Elif choice == ‘4’:

Transfer()

Elif choice == ‘5’:


Update_account()

Elif choice == ‘6’:

Apply_for_loan()

Elif choice == ‘7’:

Repay_loan()

Elif choice == ‘8’:

Show_my_account()

Elif choice == ‘9’:

Show_all_accounts()

Elif choice == ‘10’:

Delete_account()

Elif choice == ‘11’:

Print(“Exiting the system. Goodbye!”)

Break

Else:

Print(“Invalid choice. Please try again.”)

If __name__ == “__main__”:

Main_menu()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy