Completing tasks
- Python course
- Beginner
- Lesson 86/116
- 6 min
Update status with complete_task.
Completing tasks (complete_task)
Let us write a complete_task function to complete tasks. It takes an index and updates the task at that index:
def complete_task(index):
if 0 <= index < len(tasks):
tasks[index] = tasks[index] + " [done]"This appends " [done]" to the task's title. With if we check that the index is valid; so we do not go out of the list.
Why is index checking important?
Without index checking, a call like tasks[10] raises IndexError; this crashes the program. Checking with if makes the program run safely:
if 0 <= index < len(tasks):
# safe operationThis is a good software habit. It protects the code against wrong inputs and prevents the user from seeing error messages.
Practice Add the complete_task function
Define a function called complete_task that takes an index parameter. In the body check with if 0 <= index < len(tasks): and mark with tasks[index] = tasks[index] + " [done]". Call complete_task(0), then list with list_tasks().
Starter code
# Todo CLI - bos gorev listesi
tasks = []
print(tasks)
def add_task(title):
tasks.append(title)
def list_tasks():
for i, t in enumerate(tasks):
print(i, t)
add_task("Ekmek al")
add_task("Sut al")
# complete_task fonksiyonunu ekleSample solution
def complete_task(index):
if 0 <= index < len(tasks):
tasks[index] = tasks[index] + " [done]"
complete_task(0)
list_tasks()Expected output
[] 0 Buy bread [done] 1 Buy milk
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does 0 <= index < len(tasks) check?
- Is index positive
- Is index integer
- Is index large
- Is index in the list Correct answer
Explanation: This condition checks that index is in the list.
2 Complete the complete_task body
def complete_task(index):
if 0 <= index < ____(tasks):
tasks[index] = tasks[index] + " [done]"
def complete_task(index):
if 0 <= index < len(tasks):
tasks[index] = tasks[index] + " [done]"
Explanation: len(tasks) gives the list length.
3 Match the completing parts
| Term | Meaning |
|---|---|
index |
Parameter |
0 <= index < len |
Check |
tasks[index] = |
Assignment |
complete_task(0) |
Call |