Build a Mini Project in the Python Coding Language
Ready to put everything together?
In this final chapter, you’ll build a tiny command-line To‑Do app in the python coding language.
You’ll practice loops, functions, data structures, and file handling.
This ties together what you saw in Control Flow Fundamentals for Python Coding, Functions and Modules for Python Coding Beginners, and Data Structures and Files in Python Coding.
By the end, you’ll run a real script and save tasks to disk.
What you’ll build and learn:
- A command-line To‑Do app with a menu loop (list/add/complete/delete)
- Functions for each action
- An in-memory list of dicts to store tasks
- File persistence using JSON
- How to test, debug, and extend your project in the python coding language
Tip: If you need setup help, revisit Getting Started with the Python Coding Language.
If variables feel fuzzy, skim Variables and Data Types in the Python Coding Language as a quick refresher.
What We’re Building: Your Command‑Line To‑Do
You’ll run a script that shows a simple menu:
1) List tasks
2) Add a task
3) Complete a task
4) Delete a task
5) Quit
Under the hood, tasks live in memory as dictionaries.
For example, {"id": 1, "title": "Buy milk", "done": False}.
They are saved to a JSON file, so they persist between runs.
Think of the while loop as a roundabout.
Each choice exits and re-enters the loop until you choose Quit.
Step‑by‑Step Plan (10 minutes of building, 5 minutes of testing)
1) Create the file
- Make a folder for your project and create a file named todo.py.
2) Decide your data shape
- Use a list of dictionaries, one dict per task with keys: id, title, done.
3) Wire up persistence
- Save tasks to todo.json in the same folder. Load it on start, save after changes.
4) Write functions for each action
- listtasks, addtask, completetask, deletetask, loadtasks, savetasks.
5) Build the menu loop
- Show options, read input, call the right function.
6) Test incrementally
- After each action, run the script and try it. Keep the feedback loop short.
Why this structure?
- Menu loop = control flow practice from Control Flow Fundamentals for Python Coding.
- Action functions = clean, reusable code from Functions and Modules for Python Coding Beginners.
- List/dict + JSON = practical storage from Data Structures and Files in Python Coding.
Final Code Listing (copy into todo.py)
import json
from pathlib import Path
DATA_FILE = Path("todo.json")
def load_tasks():
"""Load tasks from DATA_FILE; return a list of dicts."""
if not DATA_FILE.exists():
return []
try:
with DATA_FILE.open("r", encoding="utf-8") as f:
data = json.load(f)
# Expect a list of dicts
if isinstance(data, list):
return data
return []
except json.JSONDecodeError:
print("Warning: todo.json is corrupted or empty. Starting fresh.")
return []
def save_tasks(tasks):
"""Write tasks to DATA_FILE as pretty JSON."""
with DATA_FILE.open("w", encoding="utf-8") as f:
json.dump(tasks, f, indent=2, ensure_ascii=False)
def next_id(tasks):
"""Return the next integer id based on existing tasks."""
return (max((t["id"] for t in tasks), default=0) + 1)
def list_tasks(tasks):
"""Print tasks in a nice list with numbers and status."""
if not tasks:
print("No tasks yet. Add one!")
return
print("\nYour tasks:")
for idx, t in enumerate(tasks, start=1):
status = "✓" if t.get("done") else "✗"
print(f"{idx}. [{status}] {t.get('title')} (id={t.get('id')})")
print()
def add_task(tasks):
title = input("Enter task title: ").strip()
if not title:
print("Task title cannot be empty.")
return tasks
task = {"id": next_id(tasks), "title": title, "done": False}
tasks.append(task)
print(f"Added: {title}")
return tasks
def select_index(tasks, prompt):
"""Helper to get a valid task index from the user."""
if not tasks:
print("No tasks available.")
return None
try:
n = int(input(prompt))
if 1 <= n <= len(tasks):
return n - 1
print("Please enter a number from the list.")
return None
except ValueError:
print("Please enter a valid number.")
return None
def complete_task(tasks):
list_tasks(tasks)
idx = select_index(tasks, "Complete which task number? ")
if idx is None:
return tasks
tasks[idx]["done"] = True
print(f"Completed: {tasks[idx]['title']}")
return tasks
def delete_task(tasks):
list_tasks(tasks)
idx = select_index(tasks, "Delete which task number? ")
if idx is None:
return tasks
removed = tasks.pop(idx)
print(f"Deleted: {removed['title']}")
return tasks
def show_menu():
print("\nTo-Do Menu")
print("1) List tasks")
print("2) Add task")
print("3) Complete task")
print("4) Delete task")
print("5) Quit")
def main():
tasks = load_tasks()
while True:
show_menu()
choice = input("Choose an option (1-5): ").strip()
if choice == "1":
list_tasks(tasks)
elif choice == "2":
tasks = add_task(tasks)
save_tasks(tasks)
elif choice == "3":
tasks = complete_task(tasks)
save_tasks(tasks)
elif choice == "4":
tasks = delete_task(tasks)
save_tasks(tasks)
elif choice == "5":
print("Goodbye!")
save_tasks(tasks)
break
else:
print("Please choose 1, 2, 3, 4, or 5.")
if __name__ == "__main__":
main()
Visualization tip: Picture a circle.
The while True loop is the circle; each menu choice is a spoke.
You travel from the menu to a function (spoke) and come back to the menu (circle) until you exit.
How to Run and Test (5 minutes)
- In a terminal, navigate to the folder with todo.py and run: python todo.py
- Try this flow:
1) Add two tasks
2) List tasks (you should see them with ✗)
3) Complete the first task and list again (it should show ✓)
4) Delete the second task
5) Quit and re-run the program, your changes should persist in todo.json - If you don’t have Python installed, you can run and test this project right in your browser using one of the top Python online IDEs.
What to expect:
- After adding tasks, a file named todo.json appears in the same folder.
- Re-running the app should show your saved tasks.
Debugging Checklist (when things go “hmm…”)
- Read the traceback from the bottom up. The last lines usually explain the error type and line number.
- Add quick prints. For example, print(tasks) after loading or saving to confirm the data you expect.
- Verify the file path. Is todo.json in the same folder as todo.py? Are you running python from that folder? Print(DATA_FILE.resolve()) to confirm the absolute path.
- Check JSON errors. If you manually edited todo.json and broke the syntax, you’ll see JSONDecodeError. Delete/rename the file and let the app recreate it.
- Validate inputs. Enter only numbers for menu choices and for selecting tasks.
- Keep functions small. If a function feels crowded, split it, this mirrors best practices for the python coding language.
Practical Exercise: Make It Yours
Your challenge:
- Change the menu text or emojis
- Add three tasks you actually need this week
- Mark one complete and delete one
Expected outcome:
- A todo.json file with your current tasks
- Comfort moving through the menu loop and calling functions
Tips for success:
- Edit in small steps and run often
- If something breaks, undo the last change and isolate the difference
- Skim related chapters if needed: functions in Functions and Modules for Python Coding Beginners, files in Data Structures and Files in Python Coding, and conditionals/loops in Control Flow Fundamentals for Python Coding
Optional Stretch Goals (pick 1, 2)
1) Add timestamps
- When creating a task, store created_at = time.time() and display a human-friendly date.
2) Change persistence format
- Switch from JSON to newline-delimited text (one task per line). Consider how you’ll mark done vs not done. This deepens your understanding of the python coding language’s file I/O.
3) Search or filter
- Add a menu option to search by keyword or show only incomplete tasks.
Summary and Next Steps
You just built and ran a real project in the python coding language.
It’s a menu-driven To‑Do app with functions, lists/dicts, and JSON persistence.
That’s the full flow, with input, processing, and saving working together.
Key takeaways:
- Use a while loop for interactive menus
- Keep logic in small functions
- Store structured data as a list of dictionaries
- Persist to disk (JSON) and handle errors gracefully
Continue your python coding journey:
- Read standard library docs sections you touched (json, pathlib). Skim a page, try a tiny change in your app, and repeat.
- For small daily challenges to continue your python coding journey, work through these Python exercises for beginners.
High‑five, you now have a working mini app and the momentum to keep going with the python coding language!