Control Statements: for, if, else, and while

Looping over a list

We can loop over elements of a list as follows:

We can iterate over the keys that are stored in our dictionary:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
                            

Unlike many other programming languages, which commonly use curly braces to delimit blocks of code, Python uses indentation to separate certain blocks of code. Additionally, Python does not require a semicolon at the end of each line of code.

Make sure to pay attention to how certain statements require the usage of different delimiters. A delimiter is one or more characters that separate strings of text and commonly include but are not limited to commas (,), semicolons (;), colons (:), quotes (“ ” , ‘ ’), brackets (( )), curly braces ({ }), pipes (|), and slashes (/ \).

All statements within the same block of code must be indented the same amount. Also certain statements require certain delimiters. For example:

def checkIfPositive(num): 
    if(num > 0): 
        print('The number is positive')
    else:
        print('The number is not positive')

In the code above, there is no need to worry about what the function checkIfPositive is doing. Instead it is best to realize the rigid rules behind indentation and whitespace, as being important ways to separate certains blocks of code in python.

Throughout this tutorial, we will be using # to deliminate between lines of executable code and comments. In python, comments start with the character # and extend to the end of the physical line. Lines can start with a comment or immediately following a white space, which separate lines of code and the character #, marking the start of the comment. Comments are very important to use as they allow any reader of code, including oneself, to better understand a program on line to line basis. We will be using comments frequently to show you what an individual line of code is doing.

Looking at the example that was used in the section above, we can easily insert comments throughout our code to better understand what our code is doing.

#Below is a function that takes in a number and checks if it is positive
def checkIfPositive(num): 
    if(num > 0): 
        print('The number is positive') #If the number is positive, its prints: The number is positive
    else:
        print('The number is not positive') #Otherwise, it prints: The number is not positive.

If/Else statements

Python supports if/else statements, which allow for running different code when a condition is met or not.

An else block is not required for an if-statement; if one is not provided, it is assumed to do nothing.

A common idiom in Python is to iterate over both the indices and items of a list. The enumerate function does this well.

Here's an example combining everything we've covered so far:

Iterating over dictionaries

We can iterate over the keys and values that are stored in dictionaries too:

Other iterables

The documentation refers to objects that can be iterated over as iterables. Here are some common examples:

All the containers mentioned earlier are iterable.

The while loop

Finally, we arrive at the while loop, the least-used control structure in Python (usually a for loop does better). It will execute its body as long as the condition provided resolves to True or it is broken with a break statement.