< Back

Activity 11: Conditionals

Conditionals

Conditionals give us the power of non-linear execution. However, with great power comes great responsibility, as you can end up writing some very convoluted, confusing code. To see how this can occur, let's explore conditionals a bit more carefully.

  1. Fill in the following table. For each row of the table, write what the following function prints to the terminal window. Put the result in the column on the right.

    ExecuteResult
    x = 7
    y = 3
    z = 0
    if x > y:
        if z < y:
            print(y)
        if z > x:
            print(x)
    else:
        if z < x:
            print(x)
        if z > y:
            print(y)
    
    x = 7
    y = 3
    z = 8
    if x > y:
        if z < y:
            print(y)
        if z > x:
            print(x)
    else:
        if z < x:
            print(x)
        if z > y:
            print(y)
    
    x = 7
    y = 7
    z = 0
    if x > y:
        if z < y:
            print(y)
        if z > x:
            print(x)
    else:
        if z < x:
            print(x)
        if z > y:
            print(y)
    
    x = 7
    y = 7
    z = 7
    if x > y:
        if z < y:
            print(y)
        if z > x:
            print(x)
    else:
        if z < x:
            print(x)
        if z > y:
            print(y)
    
    x = 7
    y = 10
    z = 7
    if x > y:
        if z < y:
            print(y)
        if z > x:
            print(x)
    else:
        if z < x:
            print(x)
        if z > y:
            print(y)
    
  1. We can also start mixing conditionals within our other python constructions. Let's take a look at how that affects out programs.

    ProgramOutput
    for x in range(10):
        if (x % 2) == 0:
            print(x)
    
    for x in range(10):
        if (x % 2) == 1:
            print(x)
    
    
    accumulator = 0
    for x in range(10):
        if (x % 2) == 0:
            accumulator += x
        else:
            accumulator = x
    
    print(accumulator)
    
    accumulator = 0
    for x in range(10):
        if (x % 2) == 0:
            accumulator += x
        else:
            accumulator -= x
    
    print(accumulator)