KAHIBARO Bookshelves
Discord Login Register

17.3. To-do list

Planning a Simple To-Do List Program

A to-do list app is a classic beginner project: it’s small, useful, and lets you practice user input, lists, conditions, loops, and files (if you want to save tasks).

In this chapter you’ll:

  • Design a text-based to-do list
  • Build a basic version that runs while the program is open
  • Add features: marking done, deleting tasks
  • Optionally, save and load tasks from a file

You can type and run all examples in a single .py file.


Designing the Program (Before Coding)

A basic to-do list program usually needs to:

  1. Store tasks (somewhere in memory, usually a list)
  2. Show tasks to the user
  3. Add new tasks
  4. Mark tasks as done (optional but very useful)
  5. Delete tasks (optional)
  6. Keep running until the user chooses to exit

A simple text menu is enough:

  • 1 – Show tasks
  • 2 – Add task
  • 3 – Mark task as done
  • 4 – Delete task
  • 5 – Quit

You don’t need all of these at once. Start small and add features step by step.


Step 1: Representing Tasks

We need a way to store each task. For a very first version, each task can just be a string in a list:

  • A list named tasks
  • Each item is a piece of text: "Buy milk", "Study Python"

Later, we can add a “done/not done” status.

Basic structure:

tasks = []
# add a task
tasks.append("Buy milk")
# show all tasks
for task in tasks:
    print(task)

This gives you a simple in-memory list. When the program ends, the list is lost (we’ll fix that later with files).


Step 2: A Simple Menu Loop

To make a usable to-do list, we’ll use a loop that:

  1. Prints a menu
  2. Asks the user what they want to do
  3. Runs the chosen option
  4. Repeats until the user chooses to quit
tasks = []
while True:
    print("\nTo-Do List")
    print("1. Show tasks")
    print("2. Add task")
    print("3. Quit")
    choice = input("Choose an option (1-3): ")
    if choice == "1":
        print("Showing tasks...")
    elif choice == "2":
        print("Adding a task...")
    elif choice == "3":
        print("Goodbye!")
        break
    else:
        print("Invalid choice, please try again.")

This is the “skeleton” of the program. Now we fill in the parts for showing and adding tasks.


Step 3: Showing and Adding Tasks

Showing all tasks with numbers

It’s helpful to number tasks so the user can refer to them later:

def show_tasks(tasks):
    if not tasks:  # list is empty
        print("No tasks yet!")
        return
    print("\nYour tasks:")
    for index, task in enumerate(tasks, start=1):
        print(f"{index}. {task}")
  • enumerate(tasks, start=1) gives you both the position and the task text.
  • We start at 1 because that’s more natural for users than starting at 0.

Adding a new task

A simple function for adding a task:

def add_task(tasks):
    new_task = input("Enter a new task: ").strip()
    if new_task == "":
        print("Task cannot be empty.")
        return
    tasks.append(new_task)
    print("Task added.")

Now connect these functions to the menu loop:

tasks = []
def show_tasks(tasks):
    if not tasks:
        print("No tasks yet!")
        return
    print("\nYour tasks:")
    for index, task in enumerate(tasks, start=1):
        print(f"{index}. {task}")
def add_task(tasks):
    new_task = input("Enter a new task: ").strip()
    if new_task == "":
        print("Task cannot be empty.")
        return
    tasks.append(new_task)
    print("Task added.")
while True:
    print("\nTo-Do List")
    print("1. Show tasks")
    print("2. Add task")
    print("3. Quit")
    choice = input("Choose an option (1-3): ")
    if choice == "1":
        show_tasks(tasks)
    elif choice == "2":
        add_task(tasks)
    elif choice == "3":
        print("Goodbye!")
        break
    else:
        print("Invalid choice, please try again.")

This is already a working to-do list (without saving or marking done).


Step 4: Marking Tasks as Done

We want to track whether a task is complete. Two simple options:

  1. Store tasks as strings, and decorate them
    Example: "Buy milk [DONE]"
  2. Store tasks as dictionaries
    Example: {"text": "Buy milk", "done": False}

The second option is cleaner. Let’s switch to that.

Changing task structure

Instead of:

tasks.append(new_task)  # a string

Use:

tasks.append({"text": new_task, "done": False})

Update show_tasks to display [ ] or [x]:

def show_tasks(tasks):
    if not tasks:
        print("No tasks yet!")
        return
    print("\nYour tasks:")
    for index, task in enumerate(tasks, start=1):
        status = "[x]" if task["done"] else "[ ]"
        print(f"{index}. {status} {task['text']}")

Now add a function to mark one task as done:

def mark_task_done(tasks):
    if not tasks:
        print("No tasks to mark as done.")
        return
    show_tasks(tasks)
    choice = input("Enter the number of the task to mark as done: ")
    if not choice.isdigit():
        print("Please enter a valid number.")
        return
    index = int(choice) - 1  # convert to list index
    if index < 0 or index >= len(tasks):
        print("Task number out of range.")
        return
    tasks[index]["done"] = True
    print(f"Marked task {index + 1} as done.")

Add this option to the menu:

while True:
    print("\nTo-Do List")
    print("1. Show tasks")
    print("2. Add task")
    print("3. Mark task as done")
    print("4. Quit")
    choice = input("Choose an option (1-4): ")
    if choice == "1":
        show_tasks(tasks)
    elif choice == "2":
        add_task(tasks)
    elif choice == "3":
        mark_task_done(tasks)
    elif choice == "4":
        print("Goodbye!")
        break
    else:
        print("Invalid choice, please try again.")

Now tasks stay “done” as long as the program is running.


Step 5: Deleting Tasks

Deleting lets you remove tasks completely.

We can reuse the same style of input checking from marking done.

def delete_task(tasks):
    if not tasks:
        print("No tasks to delete.")
        return
    show_tasks(tasks)
    choice = input("Enter the number of the task to delete: ")
    if not choice.isdigit():
        print("Please enter a valid number.")
        return
    index = int(choice) - 1
    if index < 0 or index >= len(tasks):
        print("Task number out of range.")
        return
    removed = tasks.pop(index)
    print(f"Deleted task: {removed['text']}")

Update the menu again:

while True:
    print("\nTo-Do List")
    print("1. Show tasks")
    print("2. Add task")
    print("3. Mark task as done")
    print("4. Delete task")
    print("5. Quit")
    choice = input("Choose an option (1-5): ")
    if choice == "1":
        show_tasks(tasks)
    elif choice == "2":
        add_task(tasks)
    elif choice == "3":
        mark_task_done(tasks)
    elif choice == "4":
        delete_task(tasks)
    elif choice == "5":
        print("Goodbye!")
        break
    else:
        print("Invalid choice, please try again.")

At this point, you have a fully interactive to-do list while the program is running.


Step 6: Saving and Loading Tasks (Optional)

Right now, tasks disappear when you close the program. To keep them, we can:

  • Write them to a file when the user quits
  • Read them from the file when the program starts

We’ll use a plain text file with one task per line.

Simple text format

We need to save both the text and the done status. One simple format:

  • 0;Buy milk → not done
  • 1;Learn Python → done

Where:

  • The first part is 0 or 1 (0 = not done, 1 = done)
  • Then a ;
  • Then the task text

Saving tasks to a file

def save_tasks(tasks, filename="tasks.txt"):
    with open(filename, "w", encoding="utf-8") as file:
        for task in tasks:
            done_flag = "1" if task["done"] else "0"
            line = done_flag + ";" + task["text"] + "\n"
            file.write(line)
    print("Tasks saved.")

Loading tasks from a file

def load_tasks(filename="tasks.txt"):
    tasks = []
    try:
        with open(filename, "r", encoding="utf-8") as file:
            for line in file:
                line = line.rstrip("\n")
                if ";" not in line:
                    continue  # skip invalid lines
                done_flag, text = line.split(";", 1)
                task = {
                    "text": text,
                    "done": (done_flag == "1")
                }
                tasks.append(task)
    except FileNotFoundError:
        # No saved tasks yet
        tasks = []
    return tasks

Now use these in your main program:

def show_tasks(tasks):
    if not tasks:
        print("No tasks yet!")
        return
    print("\nYour tasks:")
    for index, task in enumerate(tasks, start=1):
        status = "[x]" if task["done"] else "[ ]"
        print(f"{index}. {status} {task['text']}")
def add_task(tasks):
    new_task = input("Enter a new task: ").strip()
    if new_task == "":
        print("Task cannot be empty.")
        return
    tasks.append({"text": new_task, "done": False})
    print("Task added.")
def mark_task_done(tasks):
    if not tasks:
        print("No tasks to mark as done.")
        return
    show_tasks(tasks)
    choice = input("Enter the number of the task to mark as done: ")
    if not choice.isdigit():
        print("Please enter a valid number.")
        return
    index = int(choice) - 1
    if index < 0 or index >= len(tasks):
        print("Task number out of range.")
        return
    tasks[index]["done"] = True
    print(f"Marked task {index + 1} as done.")
def delete_task(tasks):
    if not tasks:
        print("No tasks to delete.")
        return
    show_tasks(tasks)
    choice = input("Enter the number of the task to delete: ")
    if not choice.isdigit():
        print("Please enter a valid number.")
        return
    index = int(choice) - 1
    if index < 0 or index >= len(tasks):
        print("Task number out of range.")
        return
    removed = tasks.pop(index)
    print(f"Deleted task: {removed['text']}")
def save_tasks(tasks, filename="tasks.txt"):
    with open(filename, "w", encoding="utf-8") as file:
        for task in tasks:
            done_flag = "1" if task["done"] else "0"
            line = done_flag + ";" + task["text"] + "\n"
            file.write(line)
    print("Tasks saved.")
def load_tasks(filename="tasks.txt"):
    tasks = []
    try:
        with open(filename, "r", encoding="utf-8") as file:
            for line in file:
                line = line.rstrip("\n")
                if ";" not in line:
                    continue
                done_flag, text = line.split(";", 1)
                task = {
                    "text": text,
                    "done": (done_flag == "1")
                }
                tasks.append(task)
    except FileNotFoundError:
        tasks = []
    return tasks
# Main program
tasks = load_tasks()
while True:
    print("\nTo-Do List")
    print("1. Show tasks")
    print("2. Add task")
    print("3. Mark task as done")
    print("4. Delete task")
    print("5. Save and quit")
    choice = input("Choose an option (1-5): ")
    if choice == "1":
        show_tasks(tasks)
    elif choice == "2":
        add_task(tasks)
    elif choice == "3":
        mark_task_done(tasks)
    elif choice == "4":
        delete_task(tasks)
    elif choice == "5":
        save_tasks(tasks)
        print("Goodbye!")
        break
    else:
        print("Invalid choice, please try again.")

Now your to-do list remembers tasks between runs.


Step 7: Possible Extensions

Once the basic version works, you can extend it in many ways. Some ideas:

  • Edit a task: change its text
  • Show only incomplete tasks
  • Show statistics: number of tasks, number done
  • Due dates or priorities: add more fields to each task dictionary
  • Sort tasks: for example, incomplete first
  • Confirm deletes: ask “Are you sure?” before deleting

Each new feature is a chance to practice functions, input handling, and data structures.


Summary

By building this to-do list, you practiced:

  • Using a loop to create a menu
  • Storing structured data in lists of dictionaries
  • Reading and validating user input
  • Modifying items in a list (marking done, deleting)
  • Saving and loading data with files

This project combines many basic Python skills into a single, useful program you can keep improving as you learn more.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms