Execute Program

Python for Programmers: Control Structures

Welcome to the Control Structures lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • This lesson covers Python's basic control structures: if, while, and for.

  • We saw ifs in an earlier lesson on significant whitespace. An if statement can also have zero or more elifs ("else if"), and zero or one else.

  • >
    def hat_size(head_circumference):
    if head_circumference < 56:
    return "small"
    elif head_circumference < 58:
    return "medium"
    elif head_circumference < 60:
    return "large"
    else:
    return "xlarge"
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    hat_size(55)
    Result:
    'small'Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    hat_size(57)
    Result:
    'medium'Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    hat_size(63)
    Result:
    'xlarge'Pass Icon
  • The while statement works the same way it does in most other languages. It runs the code block repeatedly, as long as the condition is true.

  • >
    data = [10, 5, 2]
    result = 0

    while len(data) > 0:
    result = result + data.pop()

    result
    Result:
    17Pass Icon
  • Here's a code problem:

    Use a while loop to separate numbers into two lists, odd and even. odd should contain all of the odd numbers, stored in their original order. Likewise for even numbers in even.

    Two notes:

    1. You can use the modulo operator, %, to test for whether a number is even. a_number % 2 == 0 means that the number is even.
    1. Calling .pop(0) removes and returns the first value in the list.
    numbers = [2, 5, 6, 8, 3, 1, 8]
    even = []
    odd = []
    while len(numbers) > 0:
    n = numbers.pop(0)
    if n % 2 == 0:
    even.append(n)
    else:
    odd.append(n)
    [numbers, even, odd]
    Goal:
    [
      [],
      [2, 6, 8, 8],
      [5, 3, 1],
    ]
    Yours:
    [
      [],
      [2, 6, 8, 8],
      [5, 3, 1],
    ]Pass Icon
  • Finally, Python has a for...in loop, similar to a "for each" loop in many languages, or a for...of loop in JavaScript. The for ... in loop can iterate over lists.

  • >
    sum = 0
    for n in [1, 2, 3]:
    sum = sum + n
    sum
    Result:
    6Pass Icon
  • >
    user_names = ["Amir", "Betty", "Cindy"]
    long_name_count = 0
    for user_name in user_names:
    if len(user_name) > 4:
    long_name_count = long_name_count + 1
    long_name_count
    Result:
    2Pass Icon
  • Notably, Python doesn't have a C-style for loop: for (i=0; i<10; i++). Trying to use it is a syntax error in Python.

  • Python's for loop works with many other iterable data types, like lists, tuples, and dictionaries. Even file objects are iterable: iterating over a file gives us one line of the file's text per loop iteration.

  • In an earlier lesson, we saw that list(some_dict) gives us the dictionary's keys, not its values. The for loop works in the same way: it loops over dictionary keys, not values. (This symmetry exists because for and list(...) are both built on top of Python's iteration protocols, a topic that we'll explore in a later lesson.)

  • >
    phone_book = {
    "Amir": "555-1234",
    "Betty": "555-5678"
    }

    found_amir = False
    for name in phone_book:
    if name == "Amir":
    found_amir = True
    found_amir
    Result:
    TruePass Icon
  • When we need to iterate over a dictionary's values instead of its keys, we can use its .values method, which we saw in an earlier lesson.

  • Here's a code problem:

    Write a count_order_items function that returns the total number of items ordered at a restaurant. Orders are represented as dictionaries with this structure:

    {
      "dumplings": 4,
      "rice": 3,
    }
    

    The dictionary keys are the food items' names. The dictionary values are the number of that item that the customer ordered. Since the numbers are the dictionary's values, you'll need to loop over .values().

    def count_order_items(order):
    total = 0
    for item_count in order.values():
    total = total + item_count
    return total
    [
    count_order_items({
    "dumplings": 4,
    "rice": 3,
    }),
    count_order_items({
    "ice cream cone": 2,
    }),
    ]
    Goal:
    [7, 2]
    Yours:
    [7, 2]Pass Icon
  • Iteration is everywhere in Python. Fortunately, it always works in the same way. Any fact that we learn about iteration, like "iterating over dictionaries gives us their keys", will apply anywhere. It applies when calling list, when looping with for, and when using other language features that we'll see later, including list comprehensions.

  • Iteration is a deep topic, so we'll return to it multiple times in future lessons. Eventually, we'll define our own custom objects that can be iterated with the for loop.