To be effective with Python, one needs to be comfortable using the control flow structures it provides, either to take actions or to perform the same action multiple times. In this hands-on lab, we’ll be utilizing control flow structures, like `if` statements and loops, to fix some failing automated tests, and ensure that the application works correctly.
By the time we’re finished with this hands-on lab, we should be more comfortable using `if` statements and `for` loops to write more robust functions.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Correct the `take_first` Function
Currently, the
take_first
function will raise an error if it receives an empty list of todos, but we’d like to handle that differently. Our doctests show that we should instead be returning(None, todos)
iftodos
is empty. There is more than one way that we could go about doing this:- Use a conditional statement to see if
todos
is empty right away. If it is, then return(None, todos)
. - Use a
try
statement, and if an error is raised return(None, todos)
.
For simplicity’s sake let’s use a conditional, instead of error handling, as control flow:
def take_first(todos): """ take_first receives a list of todos and removes the first todo and returns that todo and the remaining todos in a tuple >>> todos = [{'name': 'Example 1', 'body': 'This is a test task', 'points': '3'}, ... {'name': 'Task 2', 'body': 'Yet another example task', 'points': '2'}] >>> todo, todos = take_first(todos) >>> todo {'name': 'Example 1', 'body': 'This is a test task', 'points': '3'} >>> todos [{'name': 'Task 2', 'body': 'Yet another example task', 'points': '2'}] >>> todos = [] >>> take_first(todos) (None, []) """ if todos: todo = todos.pop(0) return (todo, todos) else: return (None, todos)
- Use a conditional statement to see if
- Correct the `sum_points` Function
The original version of
sum_points
takes two todo dictionaries and returns the sum of theirpoint
values. But that’s not very useful. For us to make this work for us, we’re going to modify the function so that it will take a list of todo dictionaries and sum all of the point values. We can do this easily, using afor
loop and an accumulator:def sum_points(todos): """ sum_points receives two todo dictionaries and returns the sum of their `point` values. >>> todos = [{'name': 'Example 1', 'body': 'This is a test task', 'points': '3'}, ... {'name': 'Task 2', 'body': 'Yet another example task', 'points': '2'}, ... {'name': 'Task 3', 'body': 'Third task', 'points': '5'}] >>> sum_points(todos) 10 """ total = 0 for todo in todos: total += int(todo['points']) return total