Conditional expressions

Authors

Louis Moresi

Andrew Valentine

Summary

In this section we introduce conditional execution which allows us to write algorithms that change their behaviour depending on the nature of the inputs provided.

Conditional expressions allow us to alter the behaviour of our program depending on the circumstances. To do this, we employ an if...elif...else construct, which takes the form:

if <condition>:
    [...]
elif <another condition>:
    [...]
else:
    [...]

Here, each <condition> is a ‘logical’ expression - something which is either ‘true’ or ‘false’. Each [...] denotes a block of code that is only executed if the condition is met. We can have as many elif (‘else if’) blocks as we wish, and we can omit the elif and/or else blocks entirely. At most, one block will be executed: each is tried in the order they appear in the program, until one is found for which <condition> is True. Notice that the else block does not have a condition - this is executed if none of the other conditions are met.

To make this clearer, here’s a real example, inside a function:

def condExample(x):
    if x<0:
        print("x is negative")
    elif x<=1:
        print("x is between 0 and 1 (inclusive)")
    else:
        print("x is greater than 1")

Try this function. Does everything behave as you would expect? Try deleting the elif and/or else clauses; how does this affect the output ?

Logical expressions

Logical expressions are calculations that result in either True or False. As we have already seen, they often arise by comparing the value of two variables (or a variable and a constant), such as x > 0. The comparison operators are:

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

You can check you understand how these work by testing expressions in a Python cell: for example, entering

3 > 5

should evaluate to False.

Note: an important point is that the constants True or False are Booleans, and not text. So "True" (string) is very different of True (Boolean). A possible mistake is to confound them and use "True" instead of True. In general, as soon as you want to use something based on a true/false behavior, use Boolean constants in your program.

To build more complicated expressions, you can use the Boolean operators and, or and not. An expression of the form A and B is only True if both A and B are separately True. On the other hand, A or B is True if either (or both) of A and B are themselves True. The not operator flips True to False, and vice versa. You can use parentheses to group expressions if necessary.

For example:

x > 3 and (y == 2 or not (y > 3 and x+y ==4) )

Many logical conditions can be expressed in multiple forms, for example x > 3 is identical to not x <= 3. In general, you should use the simplest form that is appropriate to your circumstances.

N.B. In some other languages, the symbols & and | are used for and and or. In Python, these symbols are ‘bitwise’ operators, and they will not give the results you expect. We will avoid using them in this course.

Test each of the operators to see if they work as expected. Be careful with the == in real programs x==3 returns True or False but, if you make a typo, x=3 will change x quietly (but 3==x is a valid test, 3=x is a SyntaxError)

Try using the and, or and not operators.

Testing for None

Another logical operator you may encounter is is. This is used to test whether two variable names refer to the same entity. This is stronger than simply testing for equality. For example:

a = 300
b = 300
print(a is b)
print(a == b)

a is b will return False, whereas a is a returns True. This may seem like a pointless detail, but we can define the == and is differently for complicated data structures and objects.

It can also be useful to distinguish between a value that has not been set, and a value that is False or 0 etc. where the logical tests may produce unexpected positives. You will often see a null default value within a function:

def printHello(name=None):
    if name is None:
        print("Hello, what is your name?")
    else:
        print("Hello "+name)
Coding scratch space