Track Your Spending (or Habits)
Understand how to log structured input to a file.
We'll cover the following...
We'll cover the following...
Let’s build a real-life Python project: a tracker!
You can use it to log spending, habits, workouts—anything you want to keep a record of.
Step 1: Simple spending logger
while True:
item = input("Enter an item (or 'done' to finish): ")
if item == "done":
break
amount = input("How much did you spend on it? ")
with open("expenses.txt", "a") as file:
file.write(item + ": $" + amount + "\n") # Concatenate the strings before writing
print("All expenses saved!")We’re asking the user for what they spent on and how much, and saving it to a file
Note: The
item,": $",amount, and"\n"are concatenated into a single string using the+operator.This single concatenated string is then written to the file using
file.write().
You just built a persistent expense logger!
Step 2: Read and display expenses
while True:
item = input("Enter an item (or 'done' to finish): ")
if item == "done":
break
amount = input("How much did you spend on it? ")
with open("expenses.txt", "a") as file:
file.write(item + ": $" + amount + "\n")
with open("expenses.txt", "r") as file:
print("Here are your expenses:")
print(file.read())
We’re reading back all past entries and showing them on screen
This displays all your logged items—even from last week!
Improve with functions
Break your code into functions for clarity:
def log_expense():
while True:
item = input("Enter an item (or 'done' to finish): ")
if item == "done":
break
amount = input("How much did you spend on it? ")
with open("expenses.txt", "a") as file:
file.write(item + ": $" + amount + "\n")
print("All expenses saved!")
def view_expenses():
with open("expenses.txt", "r") as file:
print("Here are your expenses:")
print(file.read())
log_expense()
view_expenses()Breaking the code into functions makes it easier to manage and reuse later