This guide will cover the basic of "imperative" programming in Python - controlling the flow of your code using loops and conditionals
Introduction | |
---|---|
1 | Conditionals |
1 | Loops |
2 | Exercise: Attractor Points |
Loops are code structures that allow certain lines of code to repeat multiple times under specific conditions. The most basic type of loop is one that iterates over each value within a List:
fruits = ['apples', 'oranges', 'bananas']
for fruit in fruits:
print(fruit)
The for *item* in *list*:
structure is the most basic way to construct a Loop in Python. It will runs whatever code follows this line once for each item in the List, each time setting the current item to the variable specified before the in
. In this case, it will run the print(fruit)
code three times, once for each fruit in the List. Every time the code is run, the variable fruit
is set to a different fruit in the List in order. This is often used to apply a certain kind of analysis or processing to every element within a List.
You can do the same basic kind of iteration on a dictionary using the .keys()
method, which will return a list of all the keys in the dictionary, and allow you to iterate over each entry:
myDictionary = {'a': 1, 'b': 2, 'c': 3}
for key in myDictionary.keys():
print myDictionary[key]
If you run this code, you will see that the entries are not returned in the same order that they are typed. This is because Dictionaries, unlike Lists, do not enforce a specific order. However, iterating through the keys using the .key() function will ensure that you go through each item in the Dictionary once.
In addition to iterating through every item in a List or Dictionary, Loops are often used to simply repeat a particular piece of code a specific number of times. For this, Python’s built-in range()
function is very useful. range()
takes an integer as an input and returns a List of integers starting at 0, up to but not including that value:
print(range(5))
Using the range()
function, we can set up a loop to iterate a specified number of times like this:
for i in range(5):
print('Hello')
This will simply run the code inside the Loop five times, since in effect we are creating a list of five sequential numbers, and then iterating over every item in that list. In addition, we are also storing each successive number in the variable i
, which we can also use within the loop. A common example is to combine both strategies by tying the range()
function to the length of a List (using the len()
function), and then using the iterating number to get items from that list:
fruits = ['apples', 'oranges', 'bananas']
for i in range(len(fruits)):
print(fruits[i])
Although this might seem redundant given the first example, there are times when you want to build a Loop that has access to both an item within a List, as well as an iterator which specifies its index. In such cases, you can use a special function called enumerate()
which takes in a list and returns both the item and its index:
fruits = ['apples', 'oranges', 'bananas']
for i, fruit in enumerate(fruits):
print('the ' + fruit + ' are in position ' + str(i))
While the for ... in ...
loop will serve most purposes, there is another kind of loop which will iterate over a piece of code until a certain condition is met:
i = 0
while i < 5:
print(i)
i += 1
In this case, the Loop will keep going while it’s condition is satisfied, and only stop once the variable i
obtains a value greater or equal to 5. This type of Loop can be useful if you do not know how long the Loop should be run for, or if you want to make the termination criteria somehow dynamic relative to other activities within the script. It requires a bit more setup, however, as the value tested must first be initialized (i = 0), and there has to be code within the loop which changes that value in such a way that it eventually meets the exit criteria. The +=
operator here is a shorthand in Python for adding a value to a variable. You can write the same thing explicitly like:
i = i + 1
This type of while ...
Loop is inherently more dangerous than a for ... in ...
loop, because it can easily create a situation where the Loop can never exit. In theory, such a loop will run indefinitely, although in practice it will most certainly cause Python to crash. The most dangerous kind of loop is also the simplest:
while True:
print('infinity')
because by definition it has no way to ever terminate. Surprisingly, this kind of while True
Loop does have some common uses, but you should never write code like this unless you absolutely know what you are doing (maybe try it just the once so you can get a sense of its effects).
This concludes our basic coverage of the two main types of 'flow control' structures — Conditionals and Loops. With these structures you can start to write much more complex scripts, which are not restricted to executing one command per line, and can exhibit different behavior based on changing conditions in the script. In the next module, we will introduce even more flexibility by packaging pieces of code into custom Functions and Classes so they can be easily reused in multiple places throughout the script.