Utilizing Control Flow Structures in Python

30 minutes
  • 2 Learning Objectives

About this Hands-on Lab

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) if todos is empty. There is more than one way that we could go about doing this:

  1. Use a conditional statement to see if todos is empty right away. If it is, then return (None, todos).
  2. 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)
Correct the `sum_points` Function

The original version of sum_points takes two todo dictionaries and returns the sum of their point 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 a for 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

Additional Resources

We've been tasked with building a terminal-based todo list application, and it's in its earliest stages. A co-worker has written and documented a few functions that interact with "todo" dictionaries, but there are some edge cases that aren't handled. By the time we've finished with our implementation, we should have modified the implementation for the take_first function to handle an empty list of todos, and modified sum_points to handle a list of todos.

Thankfully, our co-worker has already adjusted the doctests for these functions, to demonstrate how they should work. We have some automated tests that we can run, to ensure that our implementation meets the requirements. To run the tests, we'll use the following command from within the ~/tasker directory:

[cloud_user@host]$ python3.7 -m doctest -v tasker.py

By the time we've implemented these functions, we'll have proven our knowledge of some of Python's built-in control flow structures.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Get Started
Who’s going to be learning?

How many seats do you need?

  • $499 USD per seat per year
  • Billed Annually
  • Renews in 12 months

Ready to accelerate learning?

For over 25 licenses, a member of our sales team will walk you through a custom tailored solution for your business.


$2,495.00

Checkout
Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!