Conditional Statements

if: Conditional Statements

So now we know how to use comparison operators to compare different values in order to reach a True or False conclusion. Let’s put this to use:

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

if [condition]:
    [do something]

The Boolean expression after if is called the condition. If it is true, the indented statement runs. If not, nothing happens.

Notice how the if statement contains a colon at the end - we are indicating to Python that a block of statements follows.

Notice also that the [do something] part is indented. The first line of the condition statement is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces.

Code Output Notes
x = 1
if x > 0:
    print('x is positive')
x is positive

The condition x > 0 evaluates to true because 1 is greater than 0. So the condition is satisfied and the body of statements executes.

x = -5
if x > 0:
    print('x is positive')

None

The condition x > 0 evaluates to false because -5 is less than 0. So the condition is not satisfied nothing happens.

x = 0
if x > 0:
    print('x is positive')

None

The condition x > 0 evaluates to false because 0 is not greater than 0 (it is equal and we aren't looking for that). So the condition is not satisfied nothing happens.

my_variable = True
if my_variable:
    print("It's true!")
It's true!

The variable my_variable is a Boolean value. It evaluates to true because its value is set to True. So the condition is satisfied and the body of statements executes.

color = "red"
if color == "blue":
    print("It's blue!")

None

The variable color is a string assigned to the value "red". We compare it to the string "blue" to check if they are equal. They are not, so the condition evaluates as false. The condition is not satisfied so nothing happens.

Launch Exercise

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing – it just "passes" by and continues the code.

if x < 0: pass  # TODO: need to handle negative values!

else: Alternative Execution

A second form of the if statement is "alternative execution", in which there are two possibilities and the condition determines which one runs. The syntax looks like this:

if [condition]:
    [do something]
else:
    [do something else]

If the first condition does not evaluate to true, then the code in the body of the else header will execute. It is the alternative action. Just like with the if statement, the else statement ends with a colon and the code block within its body is indented exactly the same ways as the if code block.

Look at this conditional statement:

if x % 2 == 0: print('x is even') else: print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution.

Code Output Notes
x = 7
if x % 2 == 0:
    print('x is even')
else:
    print('x is odd')
x is odd

In this case, 7 % 2 equals 1, because when you divide 7 by 2, you get 3 with a remainder of 1. Since x % 2 == 1, then the first condition is not satisfied and the alternative code is executed.

x = 6
if x % 2 == 0:
    print('x is even')
else:
    print('x is odd')
x is even

In this case, 6 % 2 equals 0, because when you divide 6 by 2, you get 3 with a remainder of 0. Since x % 2 == 0, then the first condition is satisfied and the alternative code is not executed.

Launch Exercise

elif: Chained Conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional. It follows this format:

if [condition #1]:
    [do something]
elif [condition #2]:
    [do something else]
else:
    [do something even more different]

elif is an abbreviation of "else if". Again, exactly one branch will run. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.

Code Output Notes
x = 1
y = 2
if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')
x is less than y

1 is less than 2, so the very first condition of x < y evaluates to true, so we see x is less than y.

Note: Python ignores the second condition and the alternative.

x = 6
y = 5
if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')
x is greater than y

6 is greater than 5, so the very first condition of x < y evaluates to false. Python moves to the next condition, x > y, which evaluates as true, so we see x is greater than y.

Note: Python ignores the alternative.

x = 0
y = 0
if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')
x and y are equal

0 is equal to 0, so the very first condition of x < y evaluates to false. Python moves to the next condition, x > y, which evaluates as false. Python moves on to the alternative, so we see x and y are equal.

Launch Exercise

Nested Conditionals

One conditional can also be nested within another. We could have written the example in the previous section like this:

if x == y:      print('x and y are equal') else:      if x < y:          print('x is less than y')      else:          print('x is greater than y')

The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.

Launch Exercise