You Can Build a Simple To-Do List App in Python, Here’s How


Python is a versatile language, and even beginners can design and implement something cool with only basic knowledge. We’ll look at developing a simple to-do list app with Python that you can actually use when you’re done!




Basic Python Concepts

By now, you should know what Python is and how it works. Before diving into the code, we’ll revisit a few of the core concepts we’ll use for this to-do list application.

Variables and Data Types

A variable is a placeholder for storing data, while a data type defines the kind of data a variable can hold, such as numbers, strings, or booleans.

User Input and Output

User Input and output are the core of our application. We want users to be able to add and delete tasks and mark them as completed, failed, or deferred.

Lists and Basic List Manipulation

We’ll also use an advanced data structure called a list for this task. Lists are just collections of other data types. You can think about it like a library shelf, with each element being one of the books on that shelf.

Breaking Down the Code

We’ve already set up Visual Studio for Python previously, so this gives us a chance to test it out. We’ll make a new Python project file and store it somewhere, then decide what concepts we need for this application.


To keep things simple, we’re just using words (strings) to define our tasks. We’re going to use a list of strings to keep track of those tasks. In Python, creating a list is as simple as typing:

tasks = []

This creates a list of tasks that we can add to. The app we’re developing needs to do three things:

  • Add a task
  • Remove a task
  • Show us all the tasks in the queue

Adding a Task

So now that we have a list of tasks, we can add to it. Let’s create an add_task() function:

def add_task(task):
    tasks.append(task)
    print("Task added successfully!")

The function adds the specified task and then tells us that the task was added successfully. The confirmation is necessary because it informs us that the function is working.

Removing a Task

After adding a task, we want to be able to remove the task if it’s completed. That’s also pretty simple since lists are so powerful. Let’s add a new function to remove a task:


def remove_task(task):
    if task in tasks:
        tasks.remove(task)
        print("Task removed successfully!")
    else:
        print("Task not found.")

The code above will allow you to remove a single task once you enter the name of it. If it finds the task, it’ll remove it. What happens if the task is spelled wrong or just doesn’t exist? In that case, the code will tell us that the task doesn’t exist because it’ll look through the list and fail to find the task it’s looking for.

Showing the Task Queue

Now that we can add and remove tasks, we’ve got to have a way of displaying the list. Let’s develop a display_tasks() function that will handle this for us:

def display_tasks():
    if tasks:
        print("Your to-do list:")
        for index, task in enumerate(tasks, start=1):
            print(f"{index}. {task}")
    else:
        print("Your to-do list is empty.")

This isn’t too complicated a piece of code to understand. The first line, “if tasks:” asks Python to check if the tasks list is empty. If it isn’t, we’ll loop through it using a for loop.

For loops have a defined starting and ending point. In this example, we’ll enumerate the tasks list to get the number of tasks in the list. Then, we’ll loop through each entry and print it to the screen.


If the list is empty, we’ll just tell the user that their to-do list is empty.

Testing to See if Our Functions Work

Now that we’ve written a few functions, we must test them to see if they work. In any code, testing is crucial to ensure our code does what we want it to do. We can do this by using some test statements:

add_task("Buy groceries")
add_task("Finish homework")
display_tasks()
remove_task("Buy groceries")
display_tasks()

When we add this to the bottom of our Python code, we should get this result:

testing output for a Python to-do list app

Now that we know our functions work, they’re still sort of useless because the user can’t enter their own tasks. Let’s fix that.

We need three functions: one for taking input to add a new task, one to remove an old task, and one to display the task list:



def get_task_from_user():
    return input("Enter the task: ")


def get_task_to_remove():
    return input("Enter the task to remove: ")


def get_display_choice():
    return input("Enter 'A' to add a task, 'R' to remove a task, or 'D' to display tasks: ").upper()

Each of these functions returns whatever the user inputs to the screen. We can think about these functions as handlers to collect input from the user and use that input immediately for something else. You can think of a “return” as what you get back from the function after calling it.

Now, we want to display a menu so the user can choose which of these tasks they want to perform:

def main():
    while True:
        choice = get_display_choice()
        if choice == 'A':
            task = get_task_from_user()
            add_task(task)
        elif choice == 'R':
            task = get_task_to_remove()
            remove_task(task)
        elif choice == 'D':
            display_tasks()
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()

Let’s take a look at what this does. When we run the main() function, we will display a list of options for the user to enter (a menu). The menu prompts the user for one of three entries, then performs the selected task based on what they enter.

Suppose the user enters A to add a task. In that case, the program will wait for the user to type something in, take that input, and feed it to the add_task() function we created earlier to add a new task; the same goes for if the user types R as their input, except it runs the remove_task() function on the input instead.


If they choose D, the program displays the list of their tasks. If they enter anything else, the program prompts them that the input doesn’t fit any of the options on the menu.

This main function will continue to run indefinitely because we encapsulate it inside of a “while” loop.

Finally, the bottom line will start the main() function when we tell the program to run.

After you put these functions in, you can remove the testing code:

add_task("Buy groceries")
add_task("Finish homework")
display_tasks()
remove_task("Buy groceries")
display_tasks()

Testing and Iteration

You can find the final iteration of this code, including comments, on my GitHub if you’re interested. If you followed along properly, your output should look something like this:

testing a to-do list app menu coded in Python


Feel free to experiment with adding and removing tasks. Congratulations on completing your first fully functional Python to-do list!

Where to Go From Here

As you’ve probably noticed, the interface for this application is minimal. It looks boring with a terminal or console entry. If you’d like a challenge, you can figure out how to build a GUI for this application or expand it to include things like editing the tasks. Each of these can help you learn Python programming a bit more by exploring more complex concepts.

Depending on what you want to do with this app, you can add or change things to make it more useful for you. That’s the joy in coding—you can take a simple idea and turn it into something that suits you perfectly.



Source link

Previous articleBitcoin Difficulty Reduction Incoming? Miners Brace for a Major Shift on Aug. 14 – Bitcoin.com News