Control flow - Python Bootcamp

Constantine Lignos


  1. Basic conditionals
  2. while loops
  3. Iteration tricks
  4. Exceptions

Basic conditionals

The previous example brought up the basic structure of a Python conditional. It looks like this:

def test(x):
    """Print whether the argument evaluates as True or False."""
    if x:
        print('Evaluated as True')
        print('Evaluated as False')

Python has two built-in boolean constants True and False, but you usually don’t need to compare directly against them. You can specify “else if” clauses using elif.

while loops

Sometimes you are not sure when you’ll be done processing data. For example, let’s say you want to process data until some falg is set, but you don’t have a list of it at the beginning. The solution is to use a while loop. Assume for the moment you have a variable done that you will use to record whether you’re done:

while not done:
    # Call a magic function to do work
    result = perform_work()
    # Set done if appropriate
    done = is_good_enough(result)

This loop will automatically stop running when done is set to True.

Iteration tricks

Some things we didn’t mention earlier:

Here’s an example using both. Let’s say we want to find the index of the first negative item in a list. We iterate over the list and return the index when we find one.

for idx, item in enumerate(alist):
    if item < 0:
        result = idx
    result = None

Also, you can use continue to skip to the next iteration. For example, if you only want to process positive numbers, you might check each item and skip some.

for item in items:
    # Skip any non-positive items
    if item <= 0:



Handling is accomplished with a try…except block:

    # Do something risky here
except <name of exception to catch>:
    # Take some non-risky corrective action