Skip to content
PythonAlgorithms and Capstone Practicebeginner35 min read

Capstone: Build a Command-Line Tracker

Build a practical task tracker by combining functions, lists, dictionaries, loops, input validation, and error handling.

In this lesson, you will learn

  • ✓Explain how functions, lists, dictionaries, loops, and conditionals work together in a complete Python program.
  • ✓Build a menu-driven command-line application that accepts and validates user input.
  • ✓Add, display, complete, and delete tasks using a list of dictionaries.
  • ✓Handle blank task names, invalid menu choices, non-numeric task IDs, and missing tasks without crashing.
  • ✓Trace program execution, test edge cases, and explain the time and space complexity of important operations.

1. Plan the application before writing code

A command-line application accepts text from a terminal, performs an operation, and displays a result. Before coding, list the actions the user should be able to perform.

Our tracker will support five menu options: add a task, view all tasks, mark a task as completed, delete a task, and exit. A loop will keep showing the menu until the user chooses to exit.

We will represent each task as a dictionary and store all tasks in a list. A task dictionary will contain an integer ID, a title, and a Boolean completion status. For example, {'id': 1, 'title': 'Study Python', 'completed': False}.

The ID identifies a task independently of its current position in the list. This matters because deleting one task can change list positions, but the IDs of remaining tasks should not change.

We will divide the application into small functions. Each function will have one main responsibility, making the program easier to understand, test, and maintain.

Represent tasks with a list of dictionaries

Represent tasks with a list of dictionaries
python
tasks = [
{'id': 1, 'title': 'Study Python', 'completed': False},
{'id': 2, 'title': 'Practice loops', 'completed': True},
]
 
for task in tasks:
status = 'Done' if task['completed'] else 'Pending'
print(f"{task['id']}. {task['title']} - {status}")
Output
1. Study Python - Pending 2. Practice loops - Done

The outer list stores multiple tasks, and each dictionary stores the properties of one task. The loop visits each dictionary in order. The conditional expression chooses 'Done' when completed is True and 'Pending' otherwise. The task ID, title, and completion status are accessed using dictionary keys.

Note

The task list lives in memory while the program runs. This version does not save tasks to a file or database, so tasks disappear when the application exits.

2. Build and understand each function

Start with the smallest useful operations rather than writing the entire program as one large block. The following functions handle task creation, displaying tasks, completing tasks, and deleting tasks.

The add_task() function validates the title and appends a dictionary. It receives the next available ID from its caller instead of relying on a global variable.

The list_tasks() function displays a helpful message if there are no tasks. Otherwise, it prints each task with a readable status.

The complete_task() and delete_task() functions search for a matching ID. They return True when the requested task exists and the operation succeeds, or False when the ID does not exist.

Notice that these functions receive the task list as an argument. They can modify the list because lists are mutable, while the function's return value communicates whether the operation succeeded.

Complete and delete tasks by ID

Complete and delete tasks by ID
python
def complete_task(tasks, task_id):
for task in tasks:
if task['id'] == task_id:
task['completed'] = True
return True
return False
 
 
def delete_task(tasks, task_id):
for index, task in enumerate(tasks):
if task['id'] == task_id:
tasks.pop(index)
return True
return False
 
 
tasks = [
{'id': 1, 'title': 'Study Python', 'completed': False},
{'id': 2, 'title': 'Practice loops', 'completed': False},
]
 
print(complete_task(tasks, 2))
print(delete_task(tasks, 1))
print(tasks)
Output
True True [{'id': 2, 'title': 'Practice loops', 'completed': True}]

complete_task() searches for ID 2 and changes its completed value to True. delete_task() uses enumerate() to obtain both each list position and its dictionary. pop(index) removes the matching dictionary from the list. The return statement exits the function immediately after a successful operation. Deleting ID 1 does not change the ID of task 2.

Note

IDs must be unique for this design to work correctly. The complete application assigns each new task an ID greater than every ID currently stored, so deleting tasks does not cause an ID to be reused.

3. Validate user input and connect the menu

The input() function always returns a string. For example, input('Task ID: ') returns '12', not the integer 12. Convert that string with int() when an integer is required.

Conversion can fail if the user types text such as 'abc'. Catch ValueError so that an invalid ID produces a message instead of terminating the application.

Menu choices should also be checked. A choice outside the supported options should display an error and return to the menu. A task ID that is syntactically valid but does not exist should be handled separately from a non-numeric ID.

The main() function controls the application's flow. It creates the task list, maintains the next ID, repeatedly displays the menu, reads the user's choice, and calls the appropriate function.

The loop ends when the user selects the exit option. The break statement exits the nearest enclosing loop, which in this program is the menu loop.

Convert a task ID safely

Convert a task ID safely
python
def parse_task_id(raw_value):
try:
task_id = int(raw_value.strip())
except ValueError:
return None
 
if task_id <= 0:
return None
 
return task_id
 
 
print(parse_task_id('12'))
print(parse_task_id('abc'))
print(parse_task_id('0'))
Output
12 None None

The first input is converted into the integer 12. int('abc') raises ValueError, which is caught by the except block. Zero and negative IDs are rejected by the explicit range check. None is used here as a clear signal that the input is not a valid positive task ID.

Caution

Do not confuse a valid integer with a valid task ID. The input '12' can be converted successfully even when task 12 does not exist. Validate the format first, then check whether the requested task exists.

4. Complete project: Task Tracker

Now combine the functions into a single runnable program. This version uses only Python's standard features and requires no third-party packages.

The program supports adding tasks, displaying tasks, completing tasks, deleting tasks, and exiting. It rejects blank titles, handles invalid menu choices, and safely processes task IDs.

Copy the complete code into a file named task_tracker.py. Run it from a terminal with python task_tracker.py. On some systems, you may need to use python3 task_tracker.py.

Read the code in this order: data and helper functions, the menu, main(), and finally the if __name__ == '__main__' guard. Python defines the functions before main() calls them.

Complete runnable task tracker

Complete runnable task tracker
python
def add_task(tasks, title, task_id):
title = title.strip()
if not title:
return False
 
tasks.append({
'id': task_id,
'title': title,
'completed': False,
})
return True
 
 
def list_tasks(tasks):
if not tasks:
print('No tasks yet.')
return
 
print('\nYour tasks:')
for task in tasks:
status = 'Done' if task['completed'] else 'Pending'
print(f"{task['id']}. {task['title']} [{status}]")
 
 
def complete_task(tasks, task_id):
for task in tasks:
if task['id'] == task_id:
task['completed'] = True
return True
return False
 
 
def delete_task(tasks, task_id):
for index, task in enumerate(tasks):
if task['id'] == task_id:
tasks.pop(index)
return True
return False
 
 
def get_next_id(tasks):
return max((task['id'] for task in tasks), default=0) + 1
 
 
def read_task_id():
raw_value = input('Enter task ID: ').strip()
 
try:
task_id = int(raw_value)
except ValueError:
print('Please enter a valid integer ID.')
return None
 
if task_id <= 0:
print('Task ID must be a positive integer.')
return None
 
return task_id
 
 
def show_menu():
print('\n=== Task Tracker ===')
print('1. Add task')
print('2. View tasks')
print('3. Complete task')
print('4. Delete task')
print('5. Exit')
 
 
def main():
tasks = []
print('Welcome to Task Tracker!')
 
while True:
show_menu()
choice = input('Choose an option: ').strip()
 
if choice == '1':
title = input('Enter task title: ')
task_id = get_next_id(tasks)
 
if add_task(tasks, title, task_id):
print(f'Task added with ID {task_id}.')
else:
print('Task title cannot be blank.')
 
elif choice == '2':
list_tasks(tasks)
 
elif choice == '3':
if not tasks:
print('No tasks to complete.')
continue
 
list_tasks(tasks)
task_id = read_task_id()
if task_id is None:
continue
 
if complete_task(tasks, task_id):
print('Task marked as completed.')
else:
print('Task ID not found.')
 
elif choice == '4':
if not tasks:
print('No tasks to delete.')
continue
 
list_tasks(tasks)
task_id = read_task_id()
if task_id is None:
continue
 
if delete_task(tasks, task_id):
print('Task deleted.')
else:
print('Task ID not found.')
 
elif choice == '5':
print('Goodbye!')
break
 
else:
print('Invalid choice. Please select 1 to 5.')
 
 
if __name__ == '__main__':
main()
Output
Example session (user-entered values appear after prompts): Welcome to Task Tracker! === Task Tracker === 1. Add task 2. View tasks 3. Complete task 4. Delete task 5. Exit Choose an option: 1 Enter task title: Study Python Task added with ID 1. === Task Tracker === 1. Add task 2. View tasks 3. Complete task 4. Delete task 5. Exit Choose an option: 1 Enter task title: Practice loops Task added with ID 2. === Task Tracker === 1. Add task 2. View tasks 3. Complete task 4. Delete task 5. Exit Choose an option: 2 Your tasks: 1. Study Python [Pending] 2. Practice loops [Pending] === Task Tracker === 1. Add task 2. View tasks 3. Complete task 4. Delete task 5. Exit Choose an option: 3 Your tasks: 1. Study Python [Pending] 2. Practice loops [Pending] Enter task ID: 2 Task marked as completed. === Task Tracker === 1. Add task 2. View tasks 3. Complete task 4. Delete task 5. Exit Choose an option: 2 Your tasks: 1. Study Python [Pending] 2. Practice loops [Done] === Task Tracker === 1. Add task 2. View tasks 3. Complete task 4. Delete task 5. Exit Choose an option: 5 Goodbye!

The full code is the runnable program. The output is a representative session, not output produced without user input. main() creates an empty list and enters the menu loop. Each menu choice invokes a different function or exits the loop. Task dictionaries are modified in place when a task is completed or deleted. get_next_id() finds the largest currently stored ID and adds one. If the list is empty, max() uses zero as its default. The main guard ensures that main() runs when this file is executed directly, but not merely when it is imported as a module. The task list is held in memory only. Saving data between program runs is a possible future enhancement.

Note

The example session illustrates one path through the program. Your actual output will differ according to the options and task titles you enter.

5. Trace the program and test edge cases

A program is not complete just because its main path works. Test what happens when the list is empty, a title contains only spaces, a menu choice is unknown, an ID is not an integer, or a valid ID does not exist.

The task list changes over time. After adding a task, the list contains another dictionary. Completing a task changes a value in an existing dictionary. Deleting a task removes a dictionary from the list.

Notice that an invalid action should not accidentally change task data. For example, entering 'abc' for a task ID must not complete or delete anything.

You can test the functions independently without typing through the interactive menu. This is one reason small functions are useful: each function has inputs and observable behavior.

Test several important edge cases

Test several important edge cases
python
tasks = []
 
print(add_task(tasks, ' ', 1))
print(tasks)
 
print(add_task(tasks, 'Read a book', 1))
print(complete_task(tasks, 99))
print(delete_task(tasks, 99))
print(get_next_id(tasks))
print(tasks)
Output
False [] True False False 2 [{'id': 1, 'title': 'Read a book', 'completed': False}]

The blank title is rejected and the list remains empty. The valid task is then added with ID 1. ID 99 does not exist, so completing or deleting it returns False. The next ID is 2 because the largest existing ID is 1. The task remains unchanged after the unsuccessful operations.

Caution

This program handles ordinary input mistakes, but it does not implement file persistence, multi-user access, or protection against every possible operating-system interruption. Those are outside the scope of this beginner project.

6. Understand time and space complexity

Complexity describes how the work and memory requirements of an algorithm grow as the amount of data grows. Let n represent the number of tasks.

Adding a task with append() takes amortized O(1) time for the list operation itself. However, this program's get_next_id() scans the existing IDs to find their maximum, so assigning the next ID takes O(n) time.

Displaying all tasks takes O(n) time because each task is visited once. Searching for an ID in complete_task() or delete_task() takes O(n) time in the worst case.

Deleting an item from the middle of a Python list may also shift later elements, which takes O(n) time. The complete delete operation therefore remains O(n) in the worst case.

The list stores n task dictionaries, so the task data uses O(n) space. Completing a task uses O(1) additional space, excluding the existing data. This analysis describes growth rates, not a promise of a particular number of milliseconds.

Count the work in a linear search

Count the work in a linear search
python
def find_task(tasks, task_id):
for task in tasks:
if task['id'] == task_id:
return task
return None
 
 
tasks = [
{'id': 1, 'title': 'Read', 'completed': False},
{'id': 2, 'title': 'Write', 'completed': False},
{'id': 3, 'title': 'Review', 'completed': False},
]
 
print(find_task(tasks, 2))
print(find_task(tasks, 99))
Output
{'id': 2, 'title': 'Write', 'completed': False} None

The first search checks ID 1 and then ID 2, returning the matching dictionary. The second search checks all three dictionaries before returning None. In the worst case, the function performs a number of comparisons proportional to n, so its time complexity is O(n). The function does not create another collection proportional to the number of tasks, so its auxiliary space complexity is O(1).

Note

Big O describes asymptotic growth. It does not directly measure wall-clock time, and average-case behavior can differ from worst-case behavior.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Putting the entire application inside one large block of code.

Why it happens: Separating input handling, validation, data operations, and display into small functions makes the program easier to test and maintain.

Incorrect Approach
script.py
python
Putting the entire application inside one large block of code.
Correct Solution
script.py
python
Separate adding, listing, completing, deleting, input parsing, and menu control into focused functions.

Key takeaway: Separate adding, listing, completing, deleting, input parsing, and menu control into focused functions.

#2 Accepting a task title that contains only spaces.

Why it happens: Whitespace-only titles are not useful labels; normalize input with strip() and reject the result if it is empty.

Incorrect Approach
script.py
python
Accepting a task title that contains only spaces.
Correct Solution
script.py
python
Call strip() before validating the title, then reject it if the result is empty.

Key takeaway: Call strip() before validating the title, then reject it if the result is empty.

#3 Passing the string returned by input() directly to code that expects an integer.

Why it happens: input() returns a string, so parse and validate a task ID before passing it to logic that expects an integer.

Incorrect Approach
script.py
python
Passing the string returned by input() directly to code that expects an integer.
Correct Solution
script.py
python
Convert the input with int() inside a try/except block and handle ValueError.

Key takeaway: Convert the input with int() inside a try/except block and handle ValueError.

#4 Assuming that every positive task ID exists.

Why it happens: A positive identifier may not correspond to a stored task; check whether the ID exists and report a useful message.

Incorrect Approach
script.py
python
Assuming that every positive task ID exists.
Correct Solution
script.py
python
After validating the ID's format and range, search for the ID and handle the not-found result.

Key takeaway: After validating the ID's format and range, search for the ID and handle the not-found result.

#5 Using a task's list position as its permanent identity.

Why it happens: List positions can change when items are inserted or removed; use a stable task ID to identify a task over time.

Incorrect Approach
script.py
python
Using a task's list position as its permanent identity.
Correct Solution
script.py
python
Store a separate ID in each task dictionary so deleting an item does not change the identity of other tasks.

Key takeaway: Store a separate ID in each task dictionary so deleting an item does not change the identity of other tasks.

#6 Assuming that an in-memory list automatically saves data.

Why it happens: An in-memory list is lost when the process exits unless the program explicitly writes data to persistent storage.

Incorrect Approach
script.py
python
Assuming that an in-memory list automatically saves data.
Correct Solution
script.py
python
Understand that the list disappears when the process ends. Add file or database persistence only when you are ready to extend the project.

Key takeaway: Understand that the list disappears when the process ends. Add file or database persistence only when you are ready to extend the project.

#7 Claiming O(1) time for the entire add operation because list.append() is usually amortized O(1).

Why it happens: The append operation is usually amortized O(1), but the full add workflow may also validate input, generate IDs, and update other structures.

Incorrect Approach
script.py
python
Claiming O(1) time for the entire add operation because list.append() is usually amortized O(1).
Correct Solution
script.py
python
Analyze all work performed by the operation. In this implementation, get_next_id() scans the list and makes adding a task O(n) overall.

Key takeaway: Analyze all work performed by the operation. In this implementation, get_next_id() scans the list and makes adding a task O(n) overall.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the purpose of a capstone project?
Answer:
A capstone combines concepts from earlier lessons into a complete application. This task tracker demonstrates how Python data structures, functions, loops, conditionals, input validation, and error handling work together.
Q2:Why did you use a list of dictionaries instead of separate lists?
Answer:
Each dictionary keeps a task's related fields together, while the outer list stores all tasks. This makes each task easier to pass to functions, display, update, and delete.
Q3:Why should functions have separate responsibilities?
Answer:
Focused functions are easier to understand, test, and debug. A function for completing tasks does not need to manage the menu or parse terminal input.
Q4:How do you handle invalid user input?
Answer:
I strip surrounding whitespace, validate required text, convert numeric input inside a try/except block, reject non-positive IDs, and check whether the requested task actually exists.
Q5:Why does the project assign IDs instead of relying on list indexes?
Answer:
List positions can change after a deletion. A separate ID provides a stable identifier for each remaining task, even when its position changes.
Q6:What is the time complexity of displaying all tasks?
Answer:
O(n), because the program visits each of the n tasks once. The work grows linearly with the number of stored tasks.
Q7:What is the difference between time complexity and space complexity?
Answer:
Time complexity describes how the amount of work grows with input size. Space complexity describes how memory use grows. The task data itself requires O(n) space for n tasks.
Q8:How would you preserve tasks after the program exits?
Answer:
I would add persistence by reading the task list from a file when the program starts and writing updates back to the file. JSON would be a reasonable next step for this project because it supports lists, dictionaries, strings, numbers, and Boolean values.
Q9:What does the if __name__ == '__main__' guard do?
Answer:
It calls main() when the file is executed directly. If the file is imported as a module, the guarded call does not run automatically.
Q10:How would you test this application?
Answer:
I would test valid task creation, blank titles, empty lists, completing an existing ID, completing a missing ID, deleting a task, non-numeric input, non-positive IDs, invalid menu choices, and exiting. I would also test the helper functions independently of the interactive menu.

Key takeaways

  • A capstone project brings multiple programming concepts together into a working application.
  • Lists store collections of tasks, while dictionaries represent individual tasks and their fields.
  • Small functions make the application easier to understand, test, and maintain.
  • Input validation and exception handling prevent common mistakes from crashing the program.
  • Stable task IDs avoid relying on list positions that can change after deletion.
  • The menu loop continues until the user chooses to exit.
  • The task list is stored in memory; persistent storage requires an additional file or database feature.
  • Searching and displaying tasks take O(n) time in the worst case, while the task collection uses O(n) space.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: