import random
# Global dictionary to store account details
accounts = {}
# Display menu
def display_menu():
print("\nBank Management System")
print("1. Create Account")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Check Balance")
print("5. Exit")
# Function to create an account
def create_account():
print("\n=== Create Account ===")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
initial_deposit = float(input("Enter initial deposit amount (minimum $100): "))
if initial_deposit < 100:
print("Initial deposit must be at least $100.")
return
# Generate a unique account ID
account_id = str(random.randint(100000, 999999))
while account_id in accounts: # Ensure no duplicate ID
account_id = str(random.randint(100000, 999999))
# Store the account details
accounts[account_id] = {
"name": name,
"age": age,
"balance": initial_deposit
}
print(f"Account created successfully! Your Account ID is {account_id}")
# Function to deposit money
def deposit_money():
print("\n=== Deposit Money ===")
account_id = input("Enter your Account ID: ")
if account_id not in accounts:
print("Invalid Account ID. Please try again.")
return
deposit_amount = float(input("Enter deposit amount: "))
if deposit_amount <= 0:
print("Deposit amount must be greater than zero.")
return
accounts[account_id]["balance"] += deposit_amount
print(f"${deposit_amount} deposited successfully. New Balance: ${accounts[account_id]['balance']}")
# Function to withdraw money
def withdraw_money():
print("\n=== Withdraw Money ===")
account_id = input("Enter your Account ID: ")
if account_id not in accounts:
print("Invalid Account ID. Please try again.")
return
withdraw_amount = float(input("Enter withdrawal amount: "))
if withdraw_amount <= 0:
print("Withdrawal amount must be greater than zero.")
return
if withdraw_amount > accounts[account_id]["balance"]:
print("Insufficient funds. Transaction denied.")
return
accounts[account_id]["balance"] -= withdraw_amount
print(f"${withdraw_amount} withdrawn successfully. Remaining Balance: ${accounts[account_id]['balance']}")
# Function to check balance
def check_balance():
print("\n=== Check Balance ===")
account_id = input("Enter your Account ID: ")
if account_id not in accounts:
print("Invalid Account ID. Please try again.")
return
print(f"Account Holder: {accounts[account_id]['name']}")
print(f"Balance: ${accounts[account_id]['balance']}")
# Main program loop
def main():
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == "1":
create_account()
elif choice == "2":
deposit_money()
elif choice == "3":
withdraw_money()
elif choice == "4":
check_balance()
elif choice == "5":
print("Exiting program. Thank you for using the Bank Management System!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
main()
PythonCategory: PYTHON
LAMDA FUNCATIONS IN PYTHON
MAP FUNCTION IN PYTHON
FILTER FUNCTION IN PYTHON
Reduce Function (from functools) IN PYTHON
USING EXTERNAL LIBARIES IN PYTHON
BUID IN MODULAS IN PYTHON
WRITING TO A FILE IN PYTHON
ERROR HANDLING IN PYTHON
# Handling division by zero
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input, please enter a number.")
finally:
print("Execution completed.")
PythonNested List Comprehension Example IN PYTHON
MULTIPLICATION TABLE IN PYTHON
list Comparison In Python
Program To Manage Shopping List In Python
def display_menu():
print("\nShopping List Menu:")
print("1. Add item")
print("2. Remove item")
print("3. View list")
print("4. Exit")
def main():
shopping_list = []
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == "1":
item = input("Enter item to add: ")
shopping_list.append(item)
print(f"{item} added to the list.")
elif choice == "2":
item = input("Enter item to remove: ")
if item in shopping_list:
shopping_list.remove(item)
print(f"{item} removed from the list.")
else:
print(f"{item} is not in the list.")
elif choice == "3":
print("Shopping List:")
for item in shopping_list:
print(f"- {item}")
elif choice == "4":
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
main()
PythonMultiple Parameter in Python
Default Parameters in Python
Defining and Calling Functions in Python
While Loops In Python
FOR LOOPS IN PYTHON
Conditional Statements In Python
Dictionaries IN PYTHON
SETS IN PYTHON
TUPLES IN PYTHON
LIST IN PYTHON
PERSONAL EXPENSE TRACKER CODE IN PYTHON
Project Overview: Personal Expense Tracker
Features:
- User Authentication: Allow users to create an account and log in.
- Add Expenses: Users can add expenses with details such as amount, category (e.g., food, transportation, entertainment), and date.
- View Expenses: Display a list of expenses, filtered by date or category.
- Budget Management: Set a monthly budget and track spending against that budget.
- Data Visualization: Use charts to show spending patterns over time (daily, weekly, monthly).
- Export Data: Allow users to export their expense data to a CSV file for further analysis.
Technologies Used:
- Python: For the backend logic.
- SQLite: As a lightweight database to store user data and expenses.
- Matplotlib or Plotly: For data visualization.
- Flask: As a web framework for handling requests and rendering templates.
- HTML/CSS: For front-end development to create a user-friendly interface.
Step-by-Step Implementation:
1. Setup Environment
- Install required packages:bash
Step-by-Step Implementation:
1. Setup Environment
Install required packages:
bash
Bash2. Create the Database Model
Create a models.py
file to define the user and expense tables.
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True, nullable=False)
password = db.Column(db.String(100), nullable=False)
expenses = db.relationship('Expense', backref='owner', lazy=True)
class Expense(db.Model):
id = db.Column(db.Integer, primary_key=True)
amount = db.Column(db.Float, nullable=False)
category = db.Column(db.String(50), nullable=False)
date = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
Python3. Initialize Flask App
Create a app.py
file to handle routes and application logic.
from flask import Flask, render_template, request, redirect, url_for, flash
from models import db, User, Expense
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///expenses.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db.init_app(app)
with app.app_context():
db.create_all()
@app.route('/')
def index():
return render_template('index.html')
# Additional routes will go here
if __name__ == '__main__':
app.run(debug=True)
Python4. Implement User Authentication
Add routes for user registration and login.
from flask import session, redirect, url_for
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
new_user = User(username=username, password=password)
db.session.add(new_user)
db.session.commit()
flash('Registration successful! Please log in.')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username, password=password).first()
if user:
session['user_id'] = user.id
flash('Login successful!')
return redirect(url_for('dashboard'))
flash('Invalid username or password')
return render_template('login.html')
Python5. Add and View Expenses
Implement routes to add and view expenses
@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
if request.method == 'POST':
amount = request.form['amount']
category = request.form['category']
new_expense = Expense(amount=amount, category=category, user_id=session['user_id'])
db.session.add(new_expense)
db.session.commit()
flash('Expense added successfully!')
expenses = Expense.query.filter_by(user_id=session['user_id']).all()
return render_template('dashboard.html', expenses=expenses)
Python6. Data Visualization
Use Matplotlib to visualize expenses.
import matplotlib.pyplot as plt
@app.route('/visualize')
def visualize():
expenses = Expense.query.filter_by(user_id=session['user_id']).all()
categories = {}
for expense in expenses:
categories[expense.category] = categories.get(expense.category, 0) + expense.amount
plt.bar(categories.keys(), categories.values())
plt.xlabel('Categories')
plt.ylabel('Amount Spent')
plt.title('Expenses by Category')
plt.savefig('static/expenses.png')
return render_template('visualize.html', plot='static/expenses.png')
Python7. Exporting Data
Add functionality to export expense data to CSV.
import csv
@app.route('/export')
def export():
expenses = Expense.query.filter_by(user_id=session['user_id']).all()
with open('expenses.csv', 'w', newline='') as csvfile:
fieldnames = ['id', 'amount', 'category', 'date']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for expense in expenses:
writer.writerow({'id': expense.id, 'amount': expense.amount, 'category': expense.category, 'date': expense.date})
flash('Data exported to expenses.csv')
return redirect(url_for('dashboard'))
PythonCreate HTML Templates
Create templates/index.html
, templates/login.html
, templates/register.html
, templates/dashboard.html
, and templates/visualize.html
for the user interface.
<!-- Example: templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Tracker</title>
</head>
<body>
<h1>Welcome to the Expense Tracker</h1>
<a href="{{ url_for('register') }}">Register</a>
<a href="{{ url_for('login') }}">Login</a>
</body>
</html>
PythonConclusion
This Personal Expense Tracker project provides a comprehensive learning experience with Python and web development concepts. You can further enhance it by adding features like user roles, mobile responsiveness, and using a more sophisticated database like PostgreSQL or MongoDB.
Feel free to modify the project to suit your needs, and happy coding! If you need any more specific details or additional features, let me know!