Open In Colab

Lesson 7 Execution Control

Pragmatic AI Labs

alt text

This notebook was produced by Pragmatic AI Labs. You can continue learning about these topics by:

7.1 Learn to loop with for loops

Using Loops

The for loop is one of the most fundamental control structures in Python. One common pattern is to use the range function to generate a range of values, then to iterate on them.

Using a Simple For Loop

built in range() function creates an iterable

res = range(3)
res
range(0, 3)
for i in range(1,6):
    print(i)
1
2
3
4
5

For loop over an iterable (list)

Another common pattern is to iterate on a list (or any iterable)

friends = ["Moby", "Ahab", "Stubb"]
for friend in friends:
  print(f"With friends like {friend} who needs a Yelp review?")
With friends like Moby who needs a Yelp review?
With friends like Ahab who needs a Yelp review?
With friends like Stubb who needs a Yelp review?

7.2 Repeat with while loops

While Loops

def sea_life():
    animals = ["whale", "orca","porpoise", "moby_dick"]
    print(f"There are many creatures in the sea: {len(animals)}")
    for animal in animals:
        yield animal

animals = sea_life()
count = 0

while next(animals) != "moby_dick":
    count +=1
    print(f"hold your fire #{count}, it is just a common sea creature")
else:
    count +=1
    print(f"Fire the harpoon, we spotted Moby Dick #{count}")
There are many creatures in the sea: 4
hold your fire #1, it is just a common sea creature
hold your fire #2, it is just a common sea creature
hold your fire #3, it is just a common sea creature
Fire the harpoon, we spotted Moby Dick #4

7.3 Learn to handle exceptions

Try/Except

There is an expression in sports, “Always be prepared to do your best on your worst day”. Try/Except statements are similar. It is always a good idea to think about what happens when something goes wrong in code that is written. Try/Except blocks allow for this.

Using try/except

Catching a specific exception

whales = ["Keiko", "Shamu", "Moby Dick"]
while True:
    try:
        whale = whales.pop()
        print(f"I want this whale {whale}!")
    except IndexError:
        print("There are no more whales to be had")
        break
I want this whale Moby Dick!
I want this whale Shamu!
I want this whale Keiko!
There are no more whales to be had

Logging exceptions

It is a best practice to log exception blocks

import logging

whales = ["Keiko", "Shamu", "Moby Dick"]
while True:
    try:
        whale = whales.pop()
        print(f"I want this whale {whale}!")
    except IndexError:
        logging.exception(f"Exception Logged:  There are no more tournaments")
        print("There are no more whales to be had")
        break
I want this whale Moby Dick!
I want this whale Shamu!
I want this whale Keiko!
There are no more whales to be had

7.4 Use conditionals

Using if/else/break/continue/pass statements

Using if/elif/else blocks

If/Else statements are a common way to branch between decisions. In the example below if/elif are used to match a branch. If there are no matches, the last “else” statement is run.

def recommended_whale(emotion):
    """Recommends a whale based on emotion"""
    
    if emotion == "angry":
        print(f"You seem very {emotion}, I have just the whale for you:  Moby Dick!")
    elif emotion == "happy":
        print(f"You seem very {emotion}, I have just the whale for you:  Shamu!")
    else:
        print(f"You seem very {emotion}, I have no whale to recommend: How about a Crocodile instead?")
recommended_whale("sad")
You seem very sad, I have no whale to recommend: How about a Crocodile instead?

Single line conditional asssigment

happy = False
cloudy = False

happy = False if cloudy else True
  
happy
True

Using break

crew_members = 0
while True:
  crew_members +=1
  print(f"Moby Dick is attempting to eat crew member {crew_members}")
  if crew_members > 3:
    print(f"Moby Dick is very full, he ate {crew_members} and couldn't possibly eat any more")
    break
  
Moby Dick is attempting to eat crew member 1
Moby Dick is attempting to eat crew member 2
Moby Dick is attempting to eat crew member 3
Moby Dick is attempting to eat crew member 4
Moby Dick is very full, he ate 4 and couldn't possibly eat any more

Using continue

whales = ["Keiko", "Shamu", "Moby Dick"]
for whale in whales:
  if not whale == "Moby Dick":
    continue
  print(f"My favorite whale is {whale}")
My favorite whale is Moby Dick

Using pass

The pass keyword is often a placeholder to define a class or function

def my_func(): pass


my_func()

      File "<ipython-input-10-e2f9698e90a7>", line 4
        my_func()
              ^
    IndentationError: expected an indented block



class SomeClass: pass

some_class = SomeClass()

some_class
<__main__.SomeClass at 0x7fbdeb4e2a90>