login
Holden Web
What you'll need to know tomorrow

Making Decisions: The if Statement

So far, we've covered basic types of statements in Python—the assignment statement and the statement that calls a function. The function we've used most often is print(), which has the handy side effect of printing out the value of one or more expressions.

One of the most common needs in programming is to make a decision and act on it—for example, doing one thing if a customer answers Yes to a question, and another if they answer No. The if statement gives us this power, allowing us to take different actions depending on whether a specific condition is true.

Conditions in Python

In order to be able to make a decision, you need to evaluate some condition. The conditions we compare most frequently in Python are the comparison of two values, using operators such as < (less than) and or. You can compare for various kinds of equality or inequality:

OperatorTrue when
a == ba and b have the same value
a != ba and b do not have the same value
a < ba's value is less than b's
a <= ba's value is less than or equal to b's
a > ba's value is greater than b's
a >= ba's value is greater than or equal to b's

Comparing numbers is pretty intuitive, but keep in mind that you can't use these operators to compare complex numbers. The operands are two-dimensional, so they can't be laid out in a straight line; simple comparisons like that aren't valid. Instead, you must compare the absolute values of complex numbers, using the abs() function.

Comparing strings is useful, for example to alphabetize a list of items to make it easier ti find them. The characters in strings have a defined order, sometimes called the collation sequence. Let's suppose we want to compare strings a and b. The interpreter looks at the first character of each string. If the first character of a occurs earlier in the collation sequence than the first character of b, then a is less than b. If the first character in a is greater than the first character in b, then a is greater than b. If this initial attempt to compare the strings is inconclusive, then the next characters in the sequence of the strings are compared. The process is repeated until a determination is made or the end of the strings is reached.

If the end of one of the strings is reached and additional characters still remain in the other, then the longer of the two strings is greater. If both strings have exactly the same characters in them, they are considered equal. You may see the term "lexical comparison" used to describe this method of comparing strings. Verify the following results:

Code and output
>>> a = 23.0
>>> b = 22
>>> a == b
False
>>> a != b
True
>>> a < b
False
>>> a <= b
False
>>> a > b
True
>>> a >= b
True
>>> p1 = "Python"
>>> p2 = "Perl"
>>> p1 == p2
False
>>> p1 != p2
True
>>> p1 < p2
False
>>> p1 <= p2
False
>>> p1 > p2
True
>>> p1 >= p2
True
>>> "this+" > "this"
True
>>> "that" == "that"
True
>>> "That" == "that"
False
>>> "That".upper() == "thAT".upper()
True
>>>

The last tests show that string comparisons are case-sensitive. If you want to avoid case-sensitivity, use the upper() or lower() method to convert both strings to the same case.

In addition, you can determine whether one string appears inside another, using the in test:

Code and output
>>> x = "nan"
>>> s = "Banana"
>>> x in s
True

The result of the expression x in s is true when the substring x appears somewhere inside the string s. You can also test to find out whether a string is a member of a list or a tuple (a tuple is another type of sequence); x in l_t is true if x is an element of l_t, whether l_t is a list or a tuple.

Also, strings have several methods for you to use to determine whether the string has specific characteristics. The most important ones are shown in this table:

Method ExampleTrue when ...
s.startswith(x)String s starts with the substring x
s.endswith(x)String s ends with the substring x
s.isalnum()All characters in s are alphanumeric and there is at least one character
s.isalpha()All characters in s are alphabetic and there is at least one character
s.isdigit()All characters in s are digits and there is at least one character
s.islower()All cased characters in s are lowercase and there is at least one cased character
s.isupper()All cased characters in s are uppercase and there is at least one cased character

All of these conditions can be tested individually or, as we'll see later, in combination. You can use the if statement to choose whether or not to execute one or more statements by testing a condition and executing the statement if the condition is true. You can also choose which sets of statements to execute.

Making Decisions: if Statements

Expressions that the Python interpreter will evaluate as True or False (also called conditions) can be used to modify the actions of your program, using a basic if statement.

The if statement begins with the keyword if, followed by an expression, and ends with a colon. This line is always followed by an indented suite—one or more statements with an indentation level greater than that of the if line. If the condition is true, then the indented suite is executed. All the statements in the suite must be indented to exactly the same level. In the Python world, we use four additional spaces for each new indentation level.

With that, it's time for some actual programming.

Code
"""Detect any mention of Python in the user's input."""

uin = input("Please enter a sentence: ")
if "python" in uin.lower():
    print("You mentioned Python.")

Save it as find_python.py and run it. Note that the if statement converts the input string to lower case before checking for the substring, so you can use any combination of upper and lower case in your input. Test your program several times to verify that when the string "python" is present in your input, the program prints "You mentioned Python." and when "python" is NOT present, it does not. Make sure you test in all circumstances.

Choosing Between Alternatives: the else Clause

The basic if statement allows you to choose whether to execute an indented suite made up of one or more statements. If you want to execute one set of actions if the condition is true and execute another set if it is false, add an else clause to the if statement. The else clause follows the first indented suite, and is followed by the indented suite to execute if the if condition is false. When the condition is true, the first suite is executed; when it is false, the second suite is executed. Modify find_python.py as shown:

Code
"""Detect any mention of Python in the user's input."""

uin = input("Please enter a sentence: ")
if "python" in uin.lower():
    print("You mentioned Python.")
else:
    print("Didn't see Python there.")

Save and run it. Test your program several times, using both types of input. When your program includes alternative behaviors, it's important to test all the possible paths.

Multiple Choice Decisions

Sometimes a decision isn't as simple as choosing between A or B. You may need to test for several different conditions, then take an action on the first condition that's true. In this case, using if ... else repeatedly gives rise to a small problem. Chained if ... else statements move code to the right. else adds a level of indentation, so if we have a long chain of tests, the code moves over towards the right margin, which can make your code difficult to read. Take a look:

Observe
if (condition 1):
    suite 1
else:
    if (condition 2):
        suite 2
    else:
        if (condition 3):
            suite 3
        else:
            ...

To overcome this, Python has the elif keyword, which you can use instead of else ... if. Because a single elif incorporates the functions of both the else and the if statements, elif does not introduce an additional level of indentation:

Observe
if (condition 1):
    suite 1
elif (condition 2):
    suite 2
elif (condition 3):
    suite 3
else:
    ...

Both of our examples do the same thing, but the second one is easier to read, and presents the chain of choices much more clearly. The else clause at the end is optional; if it's included, then the suite under it will be executed if none of the conditions are true. Without an else clause, the program won't do anything at all if none of the conditions are true (it will just continue on the line after suite 3).

Now suppose we want to analyze a user's input to detect different programming languages, and respond if we don't find any of our languages mentioned. Modify your program so that it uses elif to select among the alternatives. Edit find_python.py again so it looks like this:

Code
"""Detect any mention of Pythoseveral languages in the user's input."""

uin = input("Please enter a sentence: ")
if "python" in uin.lower():
    print("You mentioned Python.")
elif "perl" in uin.lower():
    print("Aha, a Perl user!")
elif "ruby" in uin.lower():
    print("So you use Ruby, then?")
else:
    print("Didn't see Panytho languages there.")

Save and run the program. Test your results a few times. The first three times, mention one of the target languages; the fourth time don't mention a language at all. What happens if our input contains two languages? Does the program detect them both? Why or why not?

What's True and False in Python?

Python has a specific Boolean type that has only two possible values, True and False, which it produces as the result of the comparison operators we discussed above. When it comes to making decisions, however, all values in Python can be tested for truth or falsity, and almost every value is considered to be true. To a first approximation, only the following values are considered to be false:

  • Numeric zeroes (0, 0.0 and 0+0j)
  • An empty string ("")
  • An empty container ([] the empty list, () the empty tuple, {} the empty dictionary, or set() the empty set). Don't be concerned about any you aren't yet familiar with.
  • <False/li>
  • None

There are good reasons for this, mostly to do with readability. Suppose you have a variable s, which you know to contain a string, and you want to perform some action if the string isn't empty. You could write if s != "" to make the decision. You could write if len(s) > 0: or, because non-zero integers are considered true, if len(s):. But because non-empty strings are also considered true, experienced Python programmers simply write if s:. This notation might, like anything new, seem a little strange at first, but it will help your understanding to be familiar with this idiomatic form. Remember, there's a lot to learn by reading other people's code, and there's a lot of Python code in the standard library that's readily available in every Python installation.

Combining Conditions: 'and' and 'or'

Sometimes you want to take a particular action only when several conditions are true. You could do this by putting one if inside another, or you could use the and operator between the conditions. Similarly, if you want your program to execute a particular action when at least one of several conditions is true, you could use the or operator between the conditions.

Let's test the and and or operations interactively:

Code and output
>>> s = "ABC"
>>> if s.isupper() and s.startswith("A"):
...     print("s is upper case starting with A")
...
s is upper case starting with A
>>> s = "BBC"
>>> if s.isupper() and s.startswith("A"):
...     print("s is upper case starting with A")
...
(Nothing prints.)
>>> if 1 == 2 or s.endswith("C"):
...     print("Impossible happened or s ends with C")
...
Impossible happened or s ends with C
>>>

If two conditions are joined by and, the result is true only if both conditions are true. If two conditions are joined by or, the result is true if either condition is true, so even though 1 can never be equal to 2, in the second example, the condition was still true.

If somebody said to you "If the shop is open and it has cheddar, buy half a kilo of cheddar," the first thing you'd do is find out whether the shop was open. If it wasn't, then you would "short-circuit" the decision-making process by not bothering to ask whether they had cheese in stock, because you would already know you weren't going to be buying ceddar. In the same way Python's and and or short-circuit the process, so if Python has to evaluate a or b, and it finds that a is true, it returns a as the value of the expression without trying to evaluate b. In the same way, if it discovers a is false while evaluating a and b it will immediately return the (false) value of a as the result, without trying to evaluate b.

Testing for a Range of Values: Chaining Comparisons

Comparison operators have a special feature; they can be "chained." Instead of writing a < b and b < c, you can write a < b < c. Although there are slight differences between the way the Python interpreter evaluates the two expressions, for now you can regard them as equivalent.

Here are some of the other tests you can create with if statements. This program uses the while statement. Create this new program as shown:

Code
target = 63
guess = 0

while guess != target:
    guess = int(input("Guess an integer: "))
    if guess > target:
        print ("Too high...")
    elif guess < target:
        print ("Too low...")
    else:
        print ("Just right!")

Save it as guesser.py and run it, entering a few guesses. For every guess you make, the program reports whether your guess is too high or too low. With every guess, you close in on the target number. Below is the output for a typical run of the program:

Output
Guess an integer: 22
Too low...
Guess an integer: 88
Too high...
Guess an integer: 50
Too low...
Guess an integer: 67
Too high...
Guess an integer: 58
Too low...
Guess an integer: 63
Just right!
Modern Python The while loop here is covered properly in the next lesson. For now you can read it as "keep asking for guesses until the guess equals the target." Notice also that a chained comparison like 0 < guess < 100 is a natural way to test whether a value falls within a range, and reads much more like ordinary mathematical notation than the equivalent guess > 0 and guess < 100.
Wrapping It Up

You're looking good so far. But there's plenty more to learn still!

In the next lesson, we'll look at how we can write more powerful programs using loops. See you there!