Assignment Top Functions Contents


Conditionals implement decision points in a computer program. Suppose you have a program that performs some task on an image. You may well have a point in the program where you do one thing if the image is a JPEG and quite another thing if the image is a GIF file. Likely, at this point, your program will include a conditional expression to make this decision.

Before learning about conditionals, it is important to learn about logical expressions. Such expressions are the core of conditionals and loops.11

Logical expressions

A logical expression evaluates to a truth value, in essence true or false. For example, the expression x > 0 resolves to true if x is positive and false if x is negative or zero. In Python, truth is represented by the symbol True and falsehood by the symbol False. Together, these two symbols are known as Boolean values.

One can assign truth values to variables:

      >>> c = -1
      >>> z = (c > 0);

      >>> z

Here, the variable z would be assigned a value of True if c is positive; since c is negative, it is assigned a value of False. The parentheses are added to improve readability.

Logical operators

Python has the following logical operators:

== equal to
!= not equal to
>= greater than or equal to
> greater than
< less than
<= less than or equal to
and both must be true
or one or both must be true
not reverses the truth value

The first six operators are used for comparing two things, while the next two operators are the glue that joins up simpler logical expressions into more complex ones. The last operator is used to reverse a logical value from True to False and vice versa.

Beginning programmers often confuse the = operator, which is the assignment operator, with the == operator, which is the equality operator. Remember, assignment is used to change the value of a variable while equality can be used to test the value of a variable (without changing its value). Fortunately, Python does detects many attempts to use assignment when equality was intended and will complain appropriately.

Short circuiting

When evaluating a logical expression, Python evaluates the expression from left to right and stops evaluating as soon as it finds out that the expression is definitely true or definitely false. For example, when encountering the expression:

      x != 0 and y / x > 2

if x has a value of 0, the subexpression on the left side of the and connective resolves to false. At this point, there is no way for the entire expression to be true (since both the left hand side and the right hand side must be true for an and expression to be true), so the right hand side of the expression is not evaluated. Note that this expression protects against a divide-by-zero error.

If expressions

Python's if expressions are used to conditionally execute code, depending on the truth value of what is known as the test expression. One version of if has a block of code following the test expression:

Here is an example:

    if (name == "John"):
        print("What a great name you have!")

In this version, when the test expression is true (i.e., the string "John" is bound to the variable name), then the code that is indented under the if is evaluated (i.e., the compliment is printed). The indented code is known as a block and all lines in a block must be indented exactly the same amount12. If the test expression is false, however the block is not evaluated. In this text, we will enclose the test expression in parentheses even though it is not required by Python. We do that because some important programming languages require the parentheses and we want to get you into the habit.

Here is another form of if:

    if (major == "Computer Science"):
        print("Smart choice!")
        print("Ever think about changing your major?")

In this version, if has two blocks, one following the test expression and one following the else keyword. Note the colons that follow the test expression and the else; these are required by Python. As before, the first block is evaluated if the test expression is true. If the test expression is false, however, the second block is evaluated instead.

if-elif-else chains

You can chain if statements together using the elif keyword, as in:

    if (bases == 4):
        print("HOME RUN!!!")
    elif (bases == 3):
    elif (bases == 2):
    elif (bases == 1):

The block that is eventually evaluated is directly underneath the first test expression that is true, reading from top to bottom. If no test expression is true, the block associated with the else is evaluated.

What is the difference between if-elif-else chains and a sequence of unchained ifs? Consider this rewrite of the above code:

    if (bases == 4):
        print("HOME RUN!!!");
    if (bases == 3):
    if (bases == 2):
    if (bases == 1):

In the second version, there are four if statements and the else belongs to the last if. Does this behave exactly the same? The answer is, it depends. Suppose the value of the variable bases is 0. Then both versions print:


However, if the value of bases is 3, for example, the first version prints:


while the second version prints:


Why the difference? In the first version, a subsequent test expression is evaluated only if all previous test expressions evaluated to false. Once a test expression evaluates to true in an if-elif-else chain, the associated block is evaluated and no more processing of the chain is performed. Like the and and or Boolean connectives, an if-elif-else chain short-circuits.

In contrast, the sequences of ifs in the rewrite are independent; there is no short-circuiting. When the test expression of the first if fails, the test expression of the second if succeeds and triple!! is printed. Now the test expression of the third if is tested and fails as well as the test expression of the fourth if. But since the fourth if has an else, the else block is evaluated and out is printed.

It is important to know when to use an if-elif-else chain and when to use a sequence of independent ifs. If there should be only one outcome, then use an if-elif-else chain. Otherwise, use a sequence of ifs.

Practice with Boolean expressions

Here is some practice on writing complex Boolean expressions. Your task is to convert the English description into a Python Boolean expression. The variables to be used in the expressions are:

dogSize with string values "small", "medium", and "large"
dogHasSpots with Boolean values True or False
dogAge with positive integer values
dogColor with string values "white", "black", "red", and "brown"
catSize with string values "small", "medium", and "large"
catHasSpots with Boolean values True or False
catColor with string values "white", "black", "orange", and "tabby"
catEyeColor with string values "green", "brown", "blue"
catAge with positive integer values

An old dog is one with an age greater than seven years while an old cat has an age greater than or equal to nine years. A cat and a dog are young if they are younger than three years old.


Write a boolean expression that captures "Dogs that are large and have spots or cats that are white but do not have blue eyes."


(dogSize == "large" and dogHasSpots) or (catColor == "white" and catEyeColor != "blue")

Assignment Top Functions Contents