CodeBlanks Logo Icon CodeBlanks

Adding tasks

Add tasks with add_task.

Adding tasks (add_task)

Our empty list is ready. Now we write an add_task function to add tasks. The function takes a title and appends it to the list:

def add_task(title):
    tasks.append(title)

The function reads the tasks list from outside; because the list is at module level. Each call adds a new task to the list.

Calling the function

Let us call our defined function to add tasks:

add_task("Buy bread")
add_task("Buy milk")

Each call adds a new task to the list. The function can use the tasks list from outside because Python functions can access module-level variables.

This approach is common in small scripts; in bigger projects a class structure is preferred.

Practice Add the add_task function

Define a function called add_task that takes a title parameter and does tasks.append(title) in the body. Add two tasks with add_task("Buy bread") and add_task("Buy milk"). Then print print(tasks).

Starter code

main.py
# Todo CLI - bos gorev listesi
tasks = []
print(tasks)
# add_task fonksiyonunu ekle

Sample solution

main.py
def add_task(title):
    tasks.append(title)
add_task("Buy bread")
add_task("Buy milk")
print(tasks)

Expected output

[]
['Buy bread', 'Buy milk']

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does tasks.append("Buy bread") do?

  • Empties the list
  • Removes the first item
  • Raises an error
  • Adds "Buy bread" to the list Correct answer

Explanation: append adds a new item to the list.

2 Complete the add_task body

Question
def add_task(title):
    tasks.____(title)
Answer
def add_task(title):
    tasks.append(title)

Explanation: tasks.append(title) adds the item to the list.

3 Match the function parts

Term Meaning
def Definition keyword
add_task Function name
title Parameter
append List method

All lessons in Beginner