Conditionality

Conditionals are statements that specify what actions to perform when a given condition is true or false. Why is this important? It helps us tell computers to execute certain actions only when certain conditions are met. But why is this necessary? In a phrase:

"Computers are stupid."

Another way to look at this is if you have butter but no bread, you will not be able to make a sandwich - you are aware of this intuitively but a computer is not. Therefore, we need to write and execute statements that replicate our intuition i.e. make a sandwich only when you have both bread and butter.

How would the situation above look as a conditional?

have_butter = True
have_bread = True
if (have_butter and have_bread): #condition
    print("I made a sandwich :D") #action
else: 
    print("No sandwich :(") #other action

Let's look at the conditional above a little more closely.

  • The suite follows an if-else structure, which is the most common one. Simply interpreted, it means that if this condition, then do that action, else do a different action.

  • The first if statement has two True values with an and operator. The and operator will keep evaluating a statement up until the first false value, and return it.

  • This idea is known as short-circuiting and is extremely useful when we want to evaluate a certain set of conditions.

The rest of this section focuses on conditional statements. If interested about short-circuiting, you can find more information in the appendix.

All conditionals follow the if-else structure demonstrated above, but the structure can be tweaked depending on the problem we are solving. Examples below show more complex conditional suites.

age = 41
if age < 10: 
    print("Oh, you're a baby!") 
elif age >= 10 and age<=35:
    print("Still young!")
else: 
    print("Keep going, still young at heart :)")

Can you guess what the above code prints when the variable age is assigned to 41?

Alternatively, if you find yourself writing conditional statements that depend on the output of some other condition, you could nest the conditional statements - an example is shown below:

temp = 75 
if temp<90 and temp>70:
    if temp<80: 
        print("It's not too bad")
    else: 
        print("A little on the high side")
elif temp<110: 
    print("It's hot")
else: 
    print("It's hot!!!!") 

Last updated