Build the Functionality
Explore how to build key functionality for a Python Budget Tracker app by implementing core functions such as add_income and add_expense. Understand program structure, use data variables and reusable functions, and engage AI tools to generate additional features. This lesson guides you through a step-by-step coding and testing approach to solidify your programming skills in an interactive project environment.
We'll cover the following...
In the previous lesson, you:
Chatted with a simulated client and gathered needs.
Converted notes into functional requirements.
Created a clean skeleton of eight function stubs.
Now we’ll bring it to life. Starting with two core functions, then using AI to scaffold the rest. You’ll also get quick tests and a full reference solution.
We’ll keep a tiny in-memory data model:
# globals (top of your file)income = 0.0# A list of expense dictionaries, e.g. [{"category": str, "amount": float}, ...]expenses = [] # each entry: {"category": str, "amount": float}
Conventions we’ll use:
Positive amounts only.
Built-ins only, Python, no external libs / file I/O / classes.
Build the basics
We’ll implement add_income and add_expense first. These are the heartbeat of the app; everything else plugs into them.
add_income(amount)
Before we start coding our first function, let’s take a look at how a Python program is usually structured:
Variables: At the top of the file, we define variables that hold our app’s data. In our case:
income = 0.0keeps track of monthly income.expenses = []will store all expenses as a growing list.
Functions: Functions group logic into small, reusable pieces.
For example,
add_income(amount)is a function that updates the globalincome. Later, we’ll also writeadd_expense(...),print_report(...), and more.
The
mainfunction: It’s common practice to have amain()function that serves as the starting point of the program. Inside it, we call the smaller functions to perform tasks.The execution guard: At the bottom, we’ll see:
if __name__ == "__main__": main()This tells Python: If this file is run directly, start by callingmain(). It’s the entry point of the program.
Note: With this structure in place, each piece of logic has its place: data at the top, helper functions in the middle, and program execution at the bottom.
Let’s add the functionality to our income function.
income = 0.0
# A list of expense dictionaries, e.g. [{"category": str, "amount": float}, ...]
expenses = []
def add_income(amount):
"""Set or update the monthly income."""
global income
income = float(amount)
print("Income set to ${0:.2f}".format(income))
def main():
amount = input("Enter your monthly income: $")
add_income(amount)
if __name__ == "__main__":
main()add_expense(category, amount)
Now, next we have to build the expense function, but for that we need categories for expenses as indicated in the function parameters, so let’s define them first:
allowed_categories = {"Food", "Rent", "Transport", "Entertainment","Utilities", "Health", "Education", "Other"}
Now, let's use these in our function.
income = 0.0
#A list of expense dictionaries, e.g. [{"category": str, "amount": float}, ...]
expenses = []
allowed_categories = {
"Food", "Rent", "Transport", "Entertainment",
"Utilities", "Health", "Education", "Other"
}
def add_income(amount):
"""Set or update the monthly income."""
global income
income = float(amount)
print("Income set to ${0:.2f}".format(income))
def add_expense(category, amount):
"""Record an expense item."""
if category not in allowed_categories:
print("Invalid category. Please choose from: " + ", ".join(allowed_categories))
return
expenses.append({"category": category, "amount": float(amount)})
print("Expense added: {0} - ${1:.2f}".format(category, float(amount))) # Convert amount to float here
def run_cli():
"""Command-line interface."""
while True:
print("Welcome to Budget Tracker — Capstone Project")
print("1. Add income")
print("2. Add expense")
print("3. Exit")
choice = input("Choose an option (1-3): ")
if choice == "1":
amount = input("Enter your monthly income: $")
add_income(amount)
elif choice == "2":
print("\nNow, let's add an expense.")
category = input("Enter the expense category (" + ", ".join(allowed_categories) + "): ")
amount = input("Enter the expense amount: $")
add_expense(category, amount)
elif choice == "3":
print("Exiting Budget Tracker.")
break
else:
print("Invalid choice. Please select a valid option.")
if __name__ == "__main__":
run_cli()In the above code:
add_expense(category, amount):Validates the
categoryagainst allowed options.If valid, adds the expense (category + amount) to the
expenseslist and prints a confirmation.
run_cli():Displays a menu with options to:
Add income (
1)Add expense (
2)Exit (
3)
Based on user input, it calls either
add_income()oradd_expense(). The loop continues until the user exits.
Things to consider:
main()runs just once and then stops, good for testing.run_cli()keeps showing the menu in a loop until the user exits. This makes it a full app.We used
run_cliinstead ofmainbecause we want an interactive program, not a one-time test. Withrun_cli, the user can keep adding income or expenses without restarting the program.We deliberately don’t add
try/exceptyet. If a non-numeric amount is entered,float(...)will fail, so please keep it in mind.
Generate the remaining functions
Now, since we have set the base, it’s time for you to take own from here and build the rest. You can use AI Copilot to scaffold the rest of the implementation: delete_expense, total_spent, compute_category_totals, print_report, show_menu, reset_data, run_cli.
Below is an AI agent. You can use it to generate the remaining functions.
Give it a prompt, tell it what you have built and what you need rest, and ask it to generate them.
You can build on the project structure from the last lesson. Instead of jumping straight to a full solution, try implementing one function at a time. Each time you finish a function, paste it into the code widget below to see how it works. This step-by-step approach will give you a better understanding of how the whole project comes together.
If you’re unsure, click the “Show Project Skeleton” button.
Test your code
The next step is to test the code you have generated. Add it to the widget below and see how it works.
income = 0.0
# A list of expense dictionaries, e.g. [{"category": str, "amount": float}, ...]
expenses = []
allowed_categories = {
"Food", "Rent", "Transport", "Entertainment",
"Utilities", "Health", "Education", "Other"
}
def add_income(amount):
"""Set or update the monthly income."""
global income
income = float(amount)
print("Income set to ${0:.2f}".format(income))
def add_expense(category, amount):
"""Record an expense item."""
if category not in allowed_categories:
print("Invalid category. Please choose from: " + ", ".join(allowed_categories))
return
expenses.append({"category": category, "amount": float(amount)})
print("Expense added: {0} - ${1:.2f}".format(category, float(amount))) # Convert amount to float here
# Add your code
def run_cli():
"""Command-line interface."""
while True:
print("Welcome to Budget Tracker — Capstone Project")
print("1. Add income")
print("2. Add expense")
print("3. Exit")
choice = input("Choose an option (1-3): ")
if choice == "1":
amount = input("Enter your monthly income: $")
add_income(amount)
elif choice == "2":
print("\nNow, let's add an expense.")
category = input("Enter the expense category (" + ", ".join(allowed_categories) + "): ")
amount = input("Enter the expense amount: $")
add_expense(category, amount)
elif choice == "3":
print("Exiting Budget Tracker.")
break
else:
print("Invalid choice. Please select a valid option.")
if __name__ == "__main__":
run_cli()If you’re stuck, click the “Show Solution” button.
Now we have a solid working version of the Budget Tracker, but there’s more to polish, like edge-case coverage and exception handling, which we’ll tackle in the next lesson.