Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Could Someone Give me Advice for Building a Simple To-Do List App in Python?

roberrtt

New Coder
Hello there,

I am new to Python and coding in general, and I’m working on a small project to practice what I have learned so far. My goal is to create a simple command line to-do list app that can perform basic tasks like adding; removing; and viewing tasks.

Users can input a task, and it will be added to the list. Display all current tasks with numbers assigned to each for easy reference.
Users can enter the task number to remove it from the list. Maybe display completed tasks separately?

I have written some basic code that can take input and store tasks in a list; but I am struggling with organizing the functions properly. For example, how do I keep the program running until the user decides to exit? Also; how should I structure the code to make it clean and easy to maintain?

Also, I have gone through this post; Read Me - How to post your code into threads which definitely helped me out a lot.

Python:
tasks = [] 

def add_task(task): 
    tasks.append(task) 
    print(f"'{task}' added to the list.") 

def view_tasks(): 
    for idx, task in enumerate(tasks, 1): 
        print(f"{idx}. {task}") 

# Incomplete: remove_task and main program loop

Thanks in advance for help and assistance.
 
Last edited by a moderator:
I would use a database to store the task otherwise when the program finishes the list will be empty.
I would also use classes to organize the functions. Use a while loop to keep the program running with a way to exit when done.
Look into the mvc (Modal ,View, Controller) approach.

Here is an example of one way. I didn't create the database and table or write the methods but,
you get the idea.

Python:
import sqlite3 as sq

class Database:
    ''' Database class handles all database methods '''
    def __init__(self):
        pass

    def create(self):
        ''' Method to create the table '''
        pass

    def add(self, args):
        ''' Method for adding task '''
        pass

    def delete(self, id):
        ''' Method for deleting task '''
        pass

    def edit(self, id):
        ''' Method for editing task '''
        pass

    def get_task(self):
        ''' Method for getting task '''
        return False


class View:
    ''' View class will handle the menu display '''
    def __init__(self):
        self.item = {
            '1': 'Add', '2': 'Delete', '3': 'Edit',
            'q':'Quit'
        }       

class Controller:
    ''' Controll er class will handle communications
        between the classes '''
    def __init__(self, database, view):
        self.database = database
        self.view = view

if __name__ == '__main__':
    controller = Controller(Database(), View())

    while True:
        print('Menu:')
        for key, value in controller.view.item.items():
            print(f'{key}: {value}', end=' ')
        print()
        query = input('Enter the number for a menu item\n>> ')
        
        match query:
            case '1':
                task = input('Add a task\n>> ')
                controller.database.add(task)

            case '2':
                print('Task:')
                all_task = controller.database.get_task()
                if all_task:
                    for task in all_task:
                        print(task)
                    task_id = input('Enter the id for a task to delete\n>> ')
                    controller.database.delete(int(task_id))
                else:
                    print('There are not any task to delete')

            case '3':
                print('Task:')
                all_task = controller.database.get_task()
                if all_task:
                    for task in all_task:
                        print(task)
                    data = input('Enter the id and task seperated by a space to update task\n>> ').split()
                    controller.database.edit([int(data[0]),data[1]])
                else:
                    print('There are not any task to edit.')

            case 'q':
                print('Goodbye!')
                break

            case _:
                print('Error! Please use one of the menu items.')
 
Last edited:
Give this a try:-


Code:
tasks = []
completed_tasks = []

def add_task(task):
    tasks.append(task)
    print(f"'{task}' added to the list.")

def view_tasks():
    if not tasks:
        print("No tasks in the list!")
    else:
        print("\nYour To-Do List:")
        for idx, task in enumerate(tasks, 1):
            print(f"{idx}. {task}")

def remove_task(task_num):
    if 0 < task_num <= len(tasks):
        completed = tasks.pop(task_num - 1)
        completed_tasks.append(completed)
        print(f"Task '{completed}' marked as completed and removed from the list.")
    else:
        print("Invalid task number!")

def view_completed_tasks():
    if not completed_tasks:
        print("No completed tasks yet!")
    else:
        print("\nCompleted Tasks:")
        for idx, task in enumerate(completed_tasks, 1):
            print(f"{idx}. {task}")

def main():
    while True:
        print("\nWhat would you like to do?")
        print("1. Add a task")
        print("2. View tasks")
        print("3. Remove a task")
        print("4. View completed tasks")
        print("5. Exit")
        
        choice = input("Enter your choice: ").strip()
        
        if choice == "1":
            task = input("Enter a task: ").strip()
            add_task(task)
        elif choice == "2":
            view_tasks()
        elif choice == "3":
            view_tasks()
            try:
                task_num = int(input("Enter the task number to remove: ").strip())
                remove_task(task_num)
            except ValueError:
                print("Please enter a valid number!")
        elif choice == "4":
            view_completed_tasks()
        elif choice == "5":
            print("Goodbye! Happy organizing!")
            break
        else:
            print("Invalid choice, please try again!")

if __name__ == "__main__":
    main()
 
Back
Top Bottom