Python Tutorial (33) – Example: Creating a simple to-do list

Time: Column:Python views:261

A Simple To-Do List Program

A simple exercise can be creating a basic to-do list program. This program allows users to add tasks to a list and display them.

Example

# Simple To-Do List Program

# Create an empty task list
tasks = []

# Define a function to add tasks
def add_task(task):
    tasks.append(task)
    print(f"Task '{task}' has been added.")

# Define a function to display the task list
def show_tasks():
    if not tasks:
        print("The task list is empty.")
    else:
        print("Task List:")
        for index, task in enumerate(tasks, start=1):
            print(f"{index}. {task}")

# Main program loop
while True:
    print("\nChoose an option:")
    print("1. Add a task")
    print("2. Show task list")
    print("3. Exit")

    choice = input("Enter the option number: ")

    if choice == "1":
        new_task = input("Enter the new task: ")
        add_task(new_task)
    elif choice == "2":
        show_tasks()
    elif choice == "3":
        print("Exiting the program.")
        break
    else:
        print("Invalid option, please try again.")

Explanation:

  • Add a Task: The user can input a new task that gets added to the task list.

  • Show Task List: Displays all tasks in the list, or informs the user if the list is empty.

  • Exit: Allows the user to exit the program.

This simple program uses basic list operations, function definitions, and a loop to continuously prompt the user for input.