I am building a budget program, and I am new to python,a month into it. I started this project in class to push myself. Well I haven't taken a database class yet and we only briefly touch on it. The issue I am having is when I am passing a tuple to sqlite3 to put the values into the corresponding fields. I have 2 files. The functions file, that is only for the functions not relating to direct database manipulation. The other file contains all the functions for database creation to manipulation. Here is the code that is giving me problems
import budget_buddy
total_money = 0
def deposits():
"""Deposits function so we can call it later on"""
return float(input('Please enter deposit amount:'))
def input_expense_item() -> tuple:
"""
Prompt the user to enter an expense type, and the amount for the expense
:return: Tuple - expense type, amount
"""
expense_type = input("What is the expense item?\n").capitalize()
cost = None
# must ensure that the user provides a valid number! In this case, a valid decimal!
while not cost:
temp = input(f"How much was '{expense_type}'?\n")
try:
cost = float(temp)
except ValueError:
print(f"{temp} - was an invalid entry. Please make sure you entered a valid number")
# This is how to return a tuple. This means you can assign two variables when calling this function as seen below
return expense_type, cost
#def balance(expense_amount: int):
#"""Balance function to be used later on as well"""
#return total_money - expense_amount
def cash_on_hand():
"""
Cash_on_hand function, this is asking how much money not in bank
accounts do you have.
"""
return float(input('How much money do you have on hand:'))
while True:
menu_option = input("What option do you want to do?\n"
"1: Enter deposit\n"
"2: Enter cash on hand\n"
"3: Enter expenses\n"
"4: Monthly Deposit Total\n")
if menu_option == "1":
deposit_amount = deposits()
#total_money += deposit_amount
budget_buddy.insert_deposits(deposit_amount)
elif menu_option == "2":
cash_amount = cash_on_hand()
#total_money += cash_amount
budget_buddy.insert_cash(cash_amount)
elif menu_option == "3":
#new_expense_type, new_expense_amount = input_expense_item()
#print(f"The user wants to add {new_expense_type} for ${new_expense_amount}")
expense_type, cost = input_expense_item()
budget_buddy.insert_expenses(input_expense_item)
#Code below was used previously, attempting changes but keeping the code just in case for a fall back
#current_balance = balance(new_expense_amount) + cash_on_hand()
#total_money = current_balance
#print(f"Total balance is ${total_money}")
elif menu_option == "4":
budget_buddy.monthly_deposit_total()
Please ignore the comments, this code has been changed a lot since making the start of the program. And I am actively changing the way I do it.
The next is my database code,
# Importing OS module to determine desktop path
import os
import sqlite3
from datetime import datetime
from sqlite3 import Error
"""Current month with %B argument,which displays entire month name"""
current_month = datetime.now().strftime('%B')
"""Current time in year-month-day. Followed by Hour:Minute.
Used to track when data was entered.
Not used as of yet on 2020-10-17, but will be as the program develops."""
current_time = datetime.now().strftime('%Y-%m-%d')
current_time_iso = datetime.now().isoformat(sep=' ',timespec='minutes')
"""Using os module to determine the current users desktop path so we can
make the budget database file on the desktop so it is easier to find.
Sqlite3 module and Error module as well to create a connection to the
database after it is made, returning error (e) if the database does not exist."""
desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "Desktop")
default_path = os.path.join(desktop, "budget.db")
if os.path.exists(default_path):
print('Database already exists\n')
pass
else:
print(f'Creating database budget.db at {desktop}')
pass
def sql_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
print('Connected succsefully to budget.db using Sqlite3 version {}!'.format(sqlite3.version))
return conn
except Error as e:
print(e)
finally:
if not conn:
conn.close()
def monthly_table(conn):
cursorObj = conn.cursor()
cursorObj.execute(f"CREATE TABLE IF NOT EXISTS {current_month} (Deposit float, Deposit_Date real, Expense_Amount float, Expense_Type text, Cash_on_Hand float, Balance float)")
conn.commit()
print(f'Table {current_month} successfully created in budget.db')
conn = sql_connection(default_path)
if conn:
monthly_table(conn)
else:
print('Exiting')
def insert_deposits(amt):
insert_command_amt = """insert into {} (Deposit, Deposit_Date) values (?,?)""".format(current_month)
insert_amount = amt
insert_timestamp = current_time_iso
multi_insert_date_amount = insert_amount, insert_timestamp
conn.execute(insert_command_amt, multi_insert_date_amount)
conn.execute("commit;")
def monthly_deposit_total():
# mdt = monthly deposit total
mdt_query = """Select (Deposit) From {}""".format(current_month)
cursor = conn.cursor()
cursor.execute(mdt_query)
total = 0
for row in cursor:
total += row[0]
print(f"Your total deposits this month is: ${total}")
def insert_expenses(text,amt):
insert_expense_command = """insert into {} (Expense_Type, Expense_Amount) values (?,?)""".format(current_month)
insert_expense_name = str()
insert_expense_amt = amt
multi_expense_insert = insert_expense_name, insert_expense_amt
conn.execute(insert_expense_command, multi_expense_insert)
conn.execute("commit;")
My issue is the last function here,
def insert_expenses(text,amt):
insert_expense_command = """insert into {} (Expense_Type, Expense_Amount) values (?,?)""".format(current_month)
insert_expense_name = str()
insert_expense_amt = amt
multi_expense_insert = insert_expense_name, insert_expense_amt
conn.execute(insert_expense_command, multi_expense_insert)
conn.execute("commit;")
which is used by the input_expense_item function in the first code block which is my functions file.
I have been pouring over the code to find my error causing the issue but I cannot find it.
I understand it may not make sense to others why I am doing seperate tables in the database but it is how it will be done, that is not changing because I have plans for it.
The exact error I am getting is this
File "F:\Documents\GitHub\Budget_buddy\functions_for_BB.py", line 80, in budget_buddy.insert_expenses(input_expense_item)
TypeError: insert_expenses() missing 1 required positional argument: 'amt'**
The program works as intended up until it tries to push the values to the database for the expense command.
input_expense_items
returns a tuple, which is one "object", therefore, nothing is being sent to amt
when insert_expenses
is called. The tuple represents the exact object needed for the placeholder argument to execute
. If insert_expenses
takes one argument, the parsing steps can be eliminated and the argument variable will be the second arg to execute
.