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, andfor.We saw
ifs in an earlier lesson on significant whitespace. Anifstatement can also have zero or moreelifs ("else if"), and zero or oneelse.>
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'
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
hat_size(57)Result:
'medium'
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
hat_size(63)Result:
'xlarge'
The
whilestatement 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 = 0while len(data) > 0:result = result + data.pop()resultResult:
17
Here's a code problem:
Use a
whileloop to separatenumbersinto two lists,oddandeven.oddshould contain all of the odd numbers, stored in their original order. Likewise for even numbers ineven.Two notes:
- You can use the modulo operator,
%, to test for whether a number is even.a_number % 2 == 0means that the number is even.
- 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], ]
- You can use the modulo operator,
Finally, Python has a
for...inloop, similar to a "for each" loop in many languages, or afor...ofloop in JavaScript. Thefor ... inloop can iterate over lists.>
sum = 0for n in [1, 2, 3]:sum = sum + nsumResult:
6
>
user_names = ["Amir", "Betty", "Cindy"]long_name_count = 0for user_name in user_names:if len(user_name) > 4:long_name_count = long_name_count + 1long_name_countResult:
2
Notably, Python doesn't have a C-style
forloop:for (i=0; i<10; i++). Trying to use it is a syntax error in Python.Python's
forloop 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. Theforloop works in the same way: it loops over dictionary keys, not values. (This symmetry exists becauseforandlist(...)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 = Falsefor name in phone_book:if name == "Amir":found_amir = Truefound_amirResult:
True
When we need to iterate over a dictionary's values instead of its keys, we can use its
.valuesmethod, which we saw in an earlier lesson.Here's a code problem:
Write a
count_order_itemsfunction 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 = 0for item_count in order.values():total = total + item_countreturn total[count_order_items({"dumplings": 4,"rice": 3,}),count_order_items({"ice cream cone": 2,}),]- Goal:
[7, 2]
- Yours:
[7, 2]
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 withfor, 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
forloop.