Conditionals in Python

In the introductory notes on Python, we covered installation, assigning values to variables, doing input/output, and calculations. The next major piece you’ll need in order to do the assignment includes conditional expressions and assignments.

Boolean expressions

Python has values for Booleans – they are called True and False. Note that, like variable names, they are case-sensitive, so you must capitalize them as shown. There are also operators that produce Boolean values. The most obvious ones are for numeric comparisons. Consider this transcript in the Python shell:

>>> 3 < 5
True
>>> 3 > 5
False
>>> 2 < 2
False
>>> 2 <= 2
True

The last example in that block is <=, pronounced “less than or equal.” There is also >= for “greater than or equal.” You cannot have a space between the two operators: < = will be a syntax error.

Checking whether two things are exactly the same is a little tricky. The equals sign = is already used to mean variable assignment, as in:

my_quiz_score = 38

This statement above does not ask whether my_quiz_score is equal to the value 38. Instead, it sets the value of that variable to 38, and whatever value it had previously is lost.

In order to ask the question, whether a variable is equal to a certain value, you need to use a double equal sign: ==, like this:

>>> my_quiz_score == 38
True
>>> 38 == my_quiz_score
True
>>> 21 == my_quiz_score
False
>>> 19 == 19
True
>>> 19 == 21
False
>>> "nice" == "evil"
False
>>> "nice" == "nice"
True

Compound Booleans

Python also has operators from Boolean logic; they are called and, or, not. Here are a few examples involving them:

>>> 3 > 5 or 5 < 6    # becomes False or True, which is True
True
>>> 3 > 5 and 5 < 6   # becomes False and True, which is False
False
>>> not True
False
>>> not (3 > 5)
True
>>> my_quiz_score >= 0 and my_quiz_score <= 40
True

That last example determines whether the value of my_quiz_score is within a certain range: from zero to forty, inclusive.

Conditional statement

Now that we’ve seen Boolean expressions, we’re ready to explore conditional statements. You remember these from working with pseudo-code; they were statements like:

   If X > 0 then output X and stop.

The syntax in Python is a bit more regimented. There is a keyword if (must be lower case), and then the Boolean expression, followed by a colon (:) – it’s a very common mistake to forget the colon!

On the next line, and indented a few spaces, you put any statements that should be executed only if the condition is true. Here is an example:

if my_quiz_score > 32:
    print "Congratulations, that's a good score."
    grade = "A"
print "Thanks for taking the course."

You can see that the last print statement in that block is not indented. That means it is no longer controlled by the if. If we reach this code when the value of my_quiz_score is 38, the output will be:

Congratulations, that's a good score.
Thanks for taking the course.

And the variable grade will contain the text string "A". On the other hand, if my_quiz_score is 31, the output will be only the last line:

Thanks for taking the course.

It’s also possible to provide an else block that executes when the if block doesn’t. Here’s a complete program you can paste into the Python program window and run with F5:

my_quiz_score = int(raw_input("Enter your quiz score: "))

if my_quiz_score > 32:
    print "Congratulations, that's a good score."
    grade = "A"
else:
    print "I'm sure you can do better next time."
    grade = "B"

print "You earned a", grade

When you run it, try entering different values at the prompt in the shell window, and observe the results.

If/else chain

It’s a fairly common pattern to “chain together” a series of if/else conditions, something like this:

if my_quiz_score > 32:
    grade = "A"
else:
    if my_quiz_score > 24:
        grade = "B"
    else:
        if my_quiz_score > 16:
            grade = "C"
        else:
            grade = "D"

You can see that the indentation increases each time an if is embedded within the else of another if. Try tracing this code with my_quiz_score set to different values, to see what ends up being stored in grade. You may even want to revise the previous program using this technique, so it can output more than just A or B.

This chain is common enough that Python provides a shortcut for it so that the continued indentation doesn’t get out of hand. The shortcut relies on the keyword elif, and it looks like this:

if my_quiz_score > 32:
    grade = "A"
elif my_quiz_score > 24:
    grade = "B"
elif my_quiz_score > 16:
    grade = "C"
else:
    grade = "D"

This program does the same thing as the previous one, but it’s a little cleaner and shorter.