Conditional Execution

Harold Nelson

1/23/2020

Instructions

In the exercises that follow, try to predict what the python interpreter would do. Commit yourself on paper to your prediction. Then copy the code to a Jupyter notebook and run it.

Each block begins with one or more logical variables of the form condn, where the n is replaced by an integer. You should try different combinations of these variables to expand the original exercise into multiple exercises. If there are two logical variables, there are four possible combinations. By treeing out the possibilities, you can see that if there are \(n\) possibilities, there are \(2^n\) possible combinations.

if alone

If the condition after the if is true, the statement(s) in the scope of the if statement are executed. Then the following statements are executed regardless of the value of the condition.

If the condition is false, the statement(s) in the scope of the if are not executed. Regardless, the statement following the if is executed.

Note that an if nested within this structure follows the same rule.

cond1 = True
cond2 = True
if cond1:
    if cond2:
        print("Point A")
    print("Point B")    
        
print("Point C")    

if + else

If the condition after the if is true, the statement(s) in the scope of the if statement are executed; and the statements in the scope of the else are not executed

If the condition after the if is false, the stetements in the scope of the else are executed; and the statements in the scope of the if are not executed.

Then the following statements are executed regardless of the value of the condition.

cond1 = True
if cond1:
    print("Point A")
else:
    print("Point B")
print("Point C")    

if + elif

When an if is followed by one or more elif statements, the conditions following each of these are evaluated in order. As soon as one of the conditions is found to be true, the statements in the corresponding scope are executed. Then the statement following all of these is executed.

cond1 = True
cond2 = True
cond3 = True
if cond1:
    print("Point A")
elif cond2:
    print("Point B")
elif cond3:
    print("Point C")
print("Point D")    

if + elif + else

Basically this is the same as if + elif, but if none of the conditions is true, the statements in the scope of the else are executed. Then the following statement is executed.

cond1 = True
cond2 = True
cond3 = True
if cond1:
    print("Point A")
elif cond2:
    print("Point B")
elif cond3:
    print("Point C")
else:
    print("Point D")
print("Point E")