Learn Python · lesson 28 of 60 · about 8 minutes
Project: To-Do List
Give the assistant a to-do list for the day: add, complete and show tasks with a list, and catch task numbers that don't exist.
What you'll learn
- Model data with a list
- Add and remove items in response to commands
- Display numbered items
A to-do list for the day
The assistant gets a to-do list for the day. It asks for commands until Sam types quit: add puts a task on the list, done takes one off by its number and says which, and list shows them all, numbered from 1. A number that isn't a task gets a message instead of an IndexError.
The plan
Our to-do app reads commands until the user types quit:
add milkadds a taskdone 1removes task number 1listshows the tasks, numbered from 1
startswith("add ") checks how a command begins, and a slice like command[4:] keeps everything after the word and its space.
The to-do app
tasks = []
while True:
command = input("> ")
if command == "quit":
break
if command == "list":
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
elif command.startswith("add "):
tasks.append(command[4:])
elif command.startswith("done "):
number = int(command[5:])
tasks.pop(number - 1)
print(f"{len(tasks)} task(s) left")Output
> > > > 1. learn lists
> 1 task(s) leftTip
Users count from 1 but lists count from 0, so done 1 means index 0. That's why the code uses number - 1.
Tip
pop(i) gives back the item it removes, so the assistant can say which task was done in the same line that removes it.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.