Let’s first create a proper environment to work in. I’ll be using Visual Studio Code for this project, and I suggest you do the same. If you want to use something else, that’s fine too. I won’t use anything that specifically requires VSCode, it’s just to make life easier.
Let’s first create a directory to work in. If you followed Python Fundamental I, you might still have the project on your computer. Feel free to reuse that.
I called my working directory todo-app
. Put it anywhere you like to put your projects. I usually use a short path like C:\dev\todo-app
, because I hate constantly entering and looking at giant path names in my terminal and such. I do the same on Mac or Linux, and I usually have a folder called dev
in my home directory. The path would then be ~/dev/todo-app
. Nice and short!
Now it’s time to start VSCode. As you may know by now, I like the command line and usually open a shell and start VSCode with the code
command inside the project directory. But you can just as well open VS Code, go File -> Open folder and select the folder.
Now you might still have this file from the previous course, in which case you can skip this step. Otherwise, create a file called todo.py and paste the TODO app code into it:
exit = False todo_items = [] def get_argument(command): command_name, argument = command.split(" ", maxsplit=1) return argument def handle_add_command(command): task = get_argument(command) print(f"Adding task: {task}") todo_items.append(task) def handle_delete_command(command): item_number = get_argument(command) print(f"Deleting task: {item_number}") todo_items.pop(int(item_number) - 1) def handle_list_command(): index = 0 for todo_item in todo_items: index += 1 print(f"{index}. {todo_item}") def handle_open_command(command): # Read a list of todo items from a file, one per line filename = get_argument(command) filename += ".todo.txt" with open(filename, "r") as file: for line in file: todo_items.append(line.strip()) def handle_save_command(command): # Save the list to a file, one item per line filename = get_argument(command) filename += ".todo.txt" with open(filename, "w") as file: for todo_item in todo_items: file.write(f"{todo_item}\n") def process_command(command): exit = False if command.startswith("exit"): exit = True elif command.startswith("add"): handle_add_command(command) elif command.startswith("delete"): handle_delete_command(command) elif command.startswith("list"): handle_list_command() elif command.startswith("open"): handle_open_command(command) elif command.startswith("save"): handle_save_command(command) else: print("Command not recognized") return exit while not exit: command = input("Enter command: ") exit = process_command(command)
Make sure to test if the script works as-is by starting it with python todo.py
. You should get an input prompt asking for a command to be entered.