6: If

In this lesson we introduce the ability for a program to make decisions, using the “if statement.” We introduce this concept by using an example, of computing the maximum of two numbers (like the max function). The program contains two if statements.

What will happen when the input is?

5
2
Try to determine the matching output yourself, before running the code.

Example
Computing the maximum and illustrating if

Did you figure out the output correctly? Use the visualizer if necessary.

Let's walk through the second test input,

3
7
In the first two lines, x got set to 3 (the first line of input) and y got set to 7. Then we have the line

if x >= y:
It checked if x was greater than or equal to y. Since 3 is less than 7, this is false. Consequently, the following lines were not executed (they were skipped):

  print('(The maximum is x)')
  theMax = x
For the next statement

if y > x:
we checked if y was greater than x, which was true. So the lines print('(The maximum is y)') and theMax = x were executed (not skipped). Then finally, the line

print('The maximum is', theMax)
was executed.

For the first test case, the reverse happened: the first group of lines was executed, the second was skipped, and finally print('The maximum is', theMax) was again executed.

The General Structure of an If Statement

  • The first line,
    if «condition»:
    has three parts: the word if, the «CONDITION» which must be a True/False expression (more on this below), and a colon :
  • Then, a block, which means a series of commands that can be one or multiple lines long. Python determines where the block starts and stops using indentation, or in other words you need to put an equal number of spaces in front of each line of the block.

Blocks

Blocks will be used in many other places later on: in "for loops," and when writing your own functions, for example. (A common way for other programming languages to indicate blocks is with curly braces {}.) All lines in the block must have exactly the same amount of indentation: they must start with the same number of spaces. Whenever Python sees that the next line has more spaces, it assumes a new block is starting, and when there are less spaces, the block ends.

Now you will get some practice with Python blocks. The next exercise is actually 4 exercises in one. You will arrange the lines of a program to get several different results. Click on the vertical bars to open each part; you can do them in any order. As usual, in each part, drag and drop the lines of code to rearrange them.

Part 1: Unexpected indent

Scramble Exercise: Unexpected Indent
You must cause the following error:
IndentationError: unexpected indent
  • if 1000 < 10:
  • print("message 1")
  • print("message 2")
  • if 2 > 1:
  • print("message 3")

Part 2: Unexpected unindent


Scramble Exercise: Unexpected Unindent
You must cause the following error:
IndentationError: unindent does not match any outer indentation level
  • if 1000 < 10:
  • print("message 2")
  • if 2 > 1:
  • print("message 3")
  • print("message 1")

Part 3: Indent expected but not found


Scramble Exercise: Expected Indent
You must cause the following error:
IndentationError: expected an indented block
  • if 1000 < 10:
  • print("message 1")
  • print("message 2")
  • if 2 > 1:
  • print("message 3")

Part 4: Proper indentation

Scramble Exercise: Proper Indentation
Don't cause any errors!
  • if 1000 < 10:
  • print("message 1")
  • print("message 2")
  • if 2 > 1:
  • print("message 3")

True, False, and bool

So far, in the «condition» part of an if statement, we saw some simple numerical comparisons like x > y and x <= y, which evaluate as being either true or false. More generally, any expression or value that is true or false is called Boolean (named after George Boole). In Python, the bool type is used to represent Boolean values; only two bool values exist, True and False.

Example
Boolean expressions

Note that in Python, when you use the bool values True and False directly in a program, they must be capitalized or you will get an error.

Boolean comparisons

We already encountered the family of operators <, >, <= and >= which compare two numbers and give back a bool. There are two other ways to compare numbers:

  • x == y is the equality operator, it returns True if x and y are equal
  • x != y is the not-equal operator, it returns True if x and y are not equal
  • == and != also work for strings and other types of data

(There are two equal signs == here since the single equals sign already has the meaning in x = «expression» of "assign the variable x the value of «expression». Confusing = with == is a common source of bugs.)

Here is an exercise to get you started.

Coding Exercise: What's Your Sign?
Write a program that reads an integer from input, then outputs one of the capitalized words Positive, Negative, or Zero according to whether the number is positive, negative, or zero.
You may enter input for the program in the box above.

We just introduced the concept of a block (several lines grouped together at the same indentation level). You can have a block inside another block:

if password=='openSesame':
  print('User logged on.')
  if hour>17:
    print('Good evening!')
  print('Enter a command:')
Here the outer block consists of 4 lines and the inner block consists of just 1 line: 
if password=='openSesame':  
print('User logged on.')
if hour>17:
print('Good evening!')
print('Enter a command:')

Multiple Choice Exercise: Nested ifs
Which of the following outputs is not possible for this program?
Correct! If any messages are shown, it must be the case that the outer (blue) block was executed, or in other words the password was correct. In this case, even if hour>17 is false (and the inner block is skipped), the line print('Enter a command:') of the outer block will still be executed.

Later, in lesson 9, we will see that situations involving multiple boolean checks can be simplified using the else and elif (else if) commands as well as the Boolean operators "and", "or", and "not". For now, you are ready to proceed to the next lesson.