0% found this document useful (0 votes)
4 views

python Mini Project

The document describes two Python programming mini projects: a Personal Expense Tracker and a Command-Line To-Do List Manager. The Expense Tracker allows users to add, view, and summarize expenses, while the To-Do List Manager enables task management with features to add, edit, complete, and delete tasks. Both projects utilize JSON for data storage and provide a command-line interface for user interaction.

Uploaded by

khannusrat8220
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python Mini Project

The document describes two Python programming mini projects: a Personal Expense Tracker and a Command-Line To-Do List Manager. The Expense Tracker allows users to add, view, and summarize expenses, while the To-Do List Manager enables task management with features to add, edit, complete, and delete tasks. Both projects utilize JSON for data storage and provide a command-line interface for user interaction.

Uploaded by

khannusrat8220
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Mini Project:

Python Programming Mini Project: "Personal Expense


Tracker"

import json
import os
from datetime import datetime
# File where expenses will be saved
EXPENSE_FILE = "expenses.json"
# Load existing expenses from the file
def load_expenses():
if os.path.exists(EXPENSE_FILE):
with open(EXPENSE_FILE, "r") as file:
return json.load(file)
return []

# Save expenses to the file


def save_expenses(expenses):
with open(EXPENSE_FILE, "w") as file:
json.dump(expenses, file, indent=4)
# Add a new expense
def add_expense(expenses):
amount = float(input("Enter the amount: $"))
category = input("Enter the category (e.g., Food, Transport,
Entertainment): ")
date_str = input("Enter the date (YYYY-MM-DD) or press
Enter to use today's date: ")
date = date_str if date_str else
datetime.now().strftime("%Y-%m-%d")
expense = {
"amount": amount,
"category": category,
"date": date
}
expenses.append(expense)
save_expenses(expenses)
print(f"Added expense: ${amount} under {category} on
{date}")
# View total spending by category or overall
def view_summary(expenses):
print("\n1. Total spending by category")
print("2. Total overall spending")
print("3. Spending summary by time (daily, weekly, or
monthly)")
choice = input("Choose an option (1/2/3): ")
if choice == "1":
category = input("Enter the category to view: ")
total = sum(expense['amount'] for expense in expenses if
expense['category'] == category)
print(f"\nTotal spending on {category}: ${total}")
elif choice == "2":
total = sum(expense['amount'] for expense in expenses)
print(f"\nTotal overall spending: ${total}")
elif choice == "3":
time_summary(expenses)
else:
print("Invalid choice.")
# Display spending by daily, weekly, or monthly
def time_summary(expenses):
print("\n1. Daily Summary")
print("2. Monthly Summary")
choice = input("Choose an option (1/2): ")
if choice == "1":
daily_summary = {}
for expense in expenses:
date = expense['date']
daily_summary[date] = daily_summary.get(date, 0) +
expense['amount']
print("\nDaily Spending Summary:")
for date, total in daily_summary.items():
print(f"{date}: ${total}")
elif choice == "2":
monthly_summary = {}
for expense in expenses:
month = expense['date'][:7] # Extract YYYY-MM for
monthly summary
monthly_summary[month] =
monthly_summary.get(month, 0) + expense['amount']
print("\nMonthly Spending Summary:")
for month, total in monthly_summary.items():
print(f"{month}: ${total}")
else:
print("Invalid choice.")
# Main menu to drive the program
def menu():
expenses = load_expenses()
while True:
print("\nMenu:")
print("1. Add an expense")
print("2. View summary")
print("3. Exit")
choice = input("Choose an option (1/2/3): ")
if choice == "1":
add_expense(expenses)
elif choice == "2":
view_summary(expenses)
elif choice == "3":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice, please try again.")
# Run the program
if __name__ == "__main__":
menu()
Python Programming Mini Project: "Command-Line To-Do
List Manager"

import json
import os
from datetime import datetime, timedelta
# File where tasks will be saved
TASK_FILE = "tasks.json"
# Load existing tasks from the file
def load_tasks():
if os.path.exists(TASK_FILE):
with open(TASK_FILE, "r") as file:
return json.load(file)
return []
# Save tasks to the file
def save_tasks(tasks):
with open(TASK_FILE, "w") as file:
json.dump(tasks, file, indent=4)
# Add a new task
def add_task(tasks):
description = input("Enter the task description: ")
due_date_str = input("Enter the due date (YYYY-MM-DD)
or press Enter for no due date: ")
due_date = due_date_str if due_date_str else None
task = {
"description": description,
"due_date": due_date,
"completed": False
}
tasks.append(task)
save_tasks(tasks)
print(f"Task added: {description}")
# View all tasks or filtered tasks
def view_tasks(tasks, filter_type=None):
today = datetime.now().date()
print("\nTo-Do List:")
for idx, task in enumerate(tasks):
status = "Completed" if task["completed"] else "Pending"
due_date = task["due_date"]
task_due_date = datetime.strptime(due_date, "%Y-%m-
%d").date() if due_date else None
if filter_type == "completed" and not task["completed"]:
continue
elif filter_type == "pending" and task["completed"]:
continue
elif filter_type == "due_soon" and (not due_date or
task_due_date > today + timedelta(days=3)):
continue
print(f"{idx+1}. {task['description']} (Due: {due_date if
due_date else 'No due date'}) - {status}")
# Mark a task as completed
def complete_task(tasks):
task_number = int(input("Enter the task number to mark
as completed: ")) - 1
if 0 <= task_number < len(tasks):
tasks[task_number]["completed"] = True
save_tasks(tasks)
print(f"Task {task_number + 1} marked as completed.")
else:
print("Invalid task number.")
# Edit a task
def edit_task(tasks):
task_number = int(input("Enter the task number to edit: "))
-1
if 0 <= task_number < len(tasks):
new_description = input("Enter the new description: ")
new_due_date_str = input("Enter the new due date
(YYYY-MM-DD) or press Enter to keep the existing one: ")
tasks[task_number]["description"] = new_description
if new_due_date_str:
tasks[task_number]["due_date"] = new_due_date_str
save_tasks(tasks)
print(f"Task {task_number + 1} updated.")
else:
print("Invalid task number.")
# Delete a task
def delete_task(tasks):
task_number = int(input("Enter the task number to delete:
")) - 1
if 0 <= task_number < len(tasks):
removed_task = tasks.pop(task_number)
save_tasks(tasks)
print(f"Task {removed_task['description']} deleted.")
else:
print("Invalid task number.")
# Main menu to drive the program
def menu():
tasks = load_tasks()
while True:
print("\nMenu:")
print("1. Add a new task")
print("2. View all tasks")
print("3. View completed tasks")
print("4. View pending tasks")
print("5. View tasks due soon")
print("6. Mark task as completed")
print("7. Edit a task")
print("8. Delete a task")
print("9. Exit")
choice = input("Choose an option (1-9): ")

if choice == "1":
add_task(tasks)
elif choice == "2":
view_tasks(tasks)
elif choice == "3":
view_tasks(tasks, filter_type="completed")
elif choice == "4":
view_tasks(tasks, filter_type="pending")
elif choice == "5":
view_tasks(tasks, filter_type="due_soon")
elif choice == "6":
complete_task(tasks)
elif choice == "7":
edit_task(tasks)
elif choice == "8":
delete_task(tasks)
elif choice == "9":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice, please try again.")
# Run the program
if __name__ == "__main__":
menu()

You might also like