if elif else (Decision Making)

With if and (optional) elif and else you can specify to execute code based on the boolean (True and False) of a condition.

if True:
    print('code block is executed')
if False:
    print('this is not executed')
code block is executed

The code being executed is indented. You can write as many lines of code as you like.

if True:
    print('line 1')
    print('line 2')
    x = 2 * ' is a rose'
    print('A rose' + x)
line 1
line 2
A rose is a rose is a rose

Of course it’s useless to write booleans as conditions, because they will never change. Instead we want to evaluate if something is True or False.
So far we had examples using only if. With else we can specifiy a block of code that is executed if the condition is False.

j, k = 'A', 'B'
if j == k:
    print(j, '=', k)
else:
    print(j, '!=', k)
A != B

We can use if elif else if we want to evaluate multiple conditions.

a, b = 4, 8
if a > b:
    print(a, '>', b)
elif a < b:
    print(a, '<', b)
else:
    print(a, '=', b)
4 < 8

Conditionals and Lists

txt = "»Tender Buttons«, from Gertrude Stein"

We can evaluate if a (sub)string is inside a string.

if 'Butt' in txt:
    print('Butt in', txt)
Butt in »Tender Buttons«, from Gertrude Stein

We can evaluate if a specific element is inside a list.

l = [4, 0.1, 'else']
if 'else' in l:
    print('True')
True

We can reduce a list to items matching specific criteria. In the example below we reduce our list to alphabetical characters.

l = [x for x in l if str(x).isalpha()]
print(l)
['else']

Remember the function swapcase() from the for-loops notebook.

txt.swapcase()
'»tENDER bUTTONS«, FROM gERTRUDE sTEIN'

We can get the same result with conditionals. Inside a list:

txt_swapped = [x.lower() if x.isupper() else x.upper() for x in txt]
txt_swapped = ''.join(txt_swapped)
print(txt_swapped)
»tENDER bUTTONS«, FROM gERTRUDE sTEIN

We can write a more readable and reuseable function to get the same result. (Of course it’s not necessary because the function swapcase() exists already.)

def swap_case(inp_):
    # create an empty variable
    swapped = ''
    # loop through string
    for character in inp_:
        # if is lower:
        if character.islower():
            # append swapped character
            swapped += character.upper()
        # otherwise it's upper:
        else:
            swapped += character.lower()
    
    # when the loop is finished we return the result
    return swapped

Now we have defined our own function change_case. Let’s use it:

print(swap_case(txt))
»tENDER bUTTONS«, FROM gERTRUDE sTEIN