Skip to content

Commit

Permalink
Merge pull request #362 from Shashank-Shekharr/main
Browse files Browse the repository at this point in the history
Adding is_empty() and print_csv() funtions to project.
  • Loading branch information
Mrinank-Bhowmick authored Oct 1, 2023
2 parents 98ff3af + 73c6c65 commit 755db98
Showing 1 changed file with 65 additions and 28 deletions.
93 changes: 65 additions & 28 deletions projects/Expense-Tracker/main.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import sqlite3

# Connect to the database
import csv
# Connect to the database
conn = sqlite3.connect("expenses.db")
cursor = conn.cursor()

# Define SQL statements
create_table_sql = """CREATE TABLE IF NOT EXISTS expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, description TEXT, amount REAL)"""
insert_expense_sql = "INSERT INTO expenses (date, description, amount) VALUES (?, ?, ?)"
select_expenses_sql = "SELECT * FROM expenses ORDER BY date;"
delete_expense_by_id_sql = "DELETE FROM expenses WHERE id=?"
update_expense_by_id_sql = "UPDATE expenses SET description=? WHERE id=?"

# Check if the database exists, create it if not
if not conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='expenses';"
).fetchone():
if not conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='expenses';").fetchone():
cursor.execute(create_table_sql)
conn.commit()



# Define SQL statements



def add_expense():
global cursor

# Get input from user
print("Enter date (YYYY-MM-DD): ")
date = input().split()[0] + "-01"
date = input().split()[0]
print("Enter description: ")
description = input()
print("Enter amount: ")
Expand All @@ -40,34 +42,39 @@ def add_expense():

def delete_expense():
global cursor
if is_empty()==True:
print("No expenses recorded yet.")
else:

# Get ID from user
print("Enter ID to delete: ")
id = int(input())
print("Enter ID to delete: ")
id = int(input())

try:
cursor.execute(delete_expense_by_id_sql, (id,))
conn.commit()
print("Expense deleted successfully.")
except Exception as e:
print("Error deleting expense: {}".format(e))
try:
cursor.execute(delete_expense_by_id_sql, (id,))
conn.commit()
print("Expense deleted successfully.")
except Exception as e:
print("Error deleting expense: {}".format(e))


def update_expense():
global cursor

if is_empty()==True:
print("No expenses recorded yet.")
else:
# Get ID and new description from user
print("Enter ID to update: ")
id = int(input())
print("Enter new description: ")
description = input()
print("Enter ID to update: ")
id = int(input())
print("Enter new description: ")
description = input()

try:
cursor.execute(update_expense_by_id_sql, (description, id))
conn.commit()
print("Expense updated successfully.")
except Exception as e:
print("Error updating expense: {}".format(e))
try:
cursor.execute(update_expense_by_id_sql, (description, id))
conn.commit()
print("Expense updated successfully.")
except Exception as e:
print("Error updating expense: {}".format(e))


def view_expenses():
Expand All @@ -88,16 +95,42 @@ def total_expenses():
total = conn.execute("SELECT SUM(amount) FROM expenses;").fetchone()[0]
print(f"Total expenses: {total}$")

#defining function for exporting to csv
def print_csv():
#opening csv file
with open('expense.csv',"w") as csvfile:
#
csvwriter = csv.writer(csvfile)
csvwriter.writerow(["ID","DATE","Desc","description"]) # To Define heading of rows of csv
csvwriter.writerows(cursor)
expenses = conn.execute(select_expenses_sql).fetchall()
for i in expenses:
print(i)
csvwriter.writerow(i) #writing querys to csv
total = conn.execute("SELECT SUM(amount) FROM expenses;").fetchone()[0] # For total Expenses
csvwriter.writerow(["","","Total Expenses:",total]) # Printing to CSV



#defined this funtion to check is database is empty or not
def is_empty():
if conn.execute(select_expenses_sql).fetchall()==[]:

return True
else:
return False

def main_menu():
#conn=db_init()
while True:
print("\nExpense Tracker Menu:")
print("1. Add Expense")
print("2. View Expenses")
print("3. Total Expenses")
print("4. Delete Expense")
print("5. Update Expense Description")
print("6. Quit")
print("6. Export Expense")
print("7. Quit")

choice = input("Enter your choice (1-6): ")

Expand All @@ -112,12 +145,16 @@ def main_menu():
elif choice == "5":
update_expense()
elif choice == "6":
break
print_csv()
elif choice == "7":
is_empty()
else:

print("Invalid choice. Please try again.")


if __name__ == "__main__":
main_menu()


conn.close()

0 comments on commit 755db98

Please sign in to comment.