10. If Statements

Video link ../../_images/question_mark_1.svg

So far we’ve learned to create expressions, use variables, and make our own functions.

Our next step is to learn how to write code that will only run based on a certain condition. For example, we may want to draw “Game Over” text on the screen–but only if the player has run out of lives.

To do this we need to learn how to use an if statement. The if statement is also known as a conditional statement. (You can use the term “conditional statement” when you want to impress everyone how smart you are.) The if statement allows a computer to make a decision. Is it hot outside? Has the spaceship reached the edge of the screen? Has too much money been withdrawn from the account? A program can decide which block of code to run based on this statement.

10.1. Basic Comparisons

../../_images/scale.svg

Here are two example if statements. As you can probably guess, the statements see which variable is smaller, and which is larger.

Example if statements: less than, greater than
 1# Variables used in the example ``if`` statements
 2a = 4
 3b = 5
 4
 5# Basic comparisons
 6if a < b:
 7    print("a is less than b")
 8
 9if a > b:
10    print("a is greater than b")
11
12print("Done")

Try running the code. You should get output that looks like this:

Output
a is less than b
Done

Since a is less than b, the first statement will print out if this code is run. Flip the values, and the second statement will run. If both variables a and b were equal to 4, then neither of the two statements would print because 4 is not greater than 4.

Play around with the program by adjusting the values to verify the code continues to do what we expect.

10.2. Flowcharts

To show the flow of a program a flowchart may be used. Most people can follow a flowchart even without an introduction to programming. See how the flowchart below matches with the code we just ran. if statements go in diamonds and have two possible paths out of them. Regular statements go in rectangles, and have only one exit path.

../../_images/flowchart_example.svg

Flowchart

This book skips an in-depth look at flow-charting, but if you are curious and want to learn more, Wikipedia has a great article introducing how it works:

http://en.wikipedia.org/wiki/Flowchart

10.3. More Comparison Types

The prior example checked to see if variables were “greater than” or “less than.” Numbers that were equal would not pass the test. To check if values are greater than or equal, we use the two characters >= right next to each other, with no space between. Let’s adjust our prior code sample:

Example if statements: less than or equal, greater than or equal
1if a <= b:
2    print("a is less than or equal to b")
3
4if a >= b:
5    print("a is greater than or equal to b")

The <= and >= symbols must be used in order, and there may not be a space between them. For example, =< will not work, nor will < =.

When writing these statements out on actual paper, some new programmers like to use the symbol, because that’s what we learned in math. For example:

if a ≤ b:

This symbol doesn’t actually work in a program. Plus most people don’t know how to type it on the keyboard. (Just in case you are curious, to type it hold down the ‘alt’ key while typing 243 on the number pad.) So when writing out code, particularly on paper, remember to use the two characters <= and not the one character symbol. If you encounter a written test or quiz, make sure to write it out correctly and not lose points.

The next set of code checks to see if two items are equal or not. If we want to check for equality, we use two equals signs in a row: ==. The operator for not equal is !=. Here they are in action. Add them to the bottom of the other code we were working on, and try them out.

Example if statements: “equal” and “not equal”
1# Equal
2if a == b:
3    print("a is equal to b")
4
5# Not equal
6if a != b:
7    print("a and b are not equal")

Attention

Learn when to use = and ==.

It is very easy to mix up when to use == and =. Use == if you are asking if they are equal, use = if you are assigning a value.

The two most common mistakes in mixing the = and == operators are demonstrated below:

1# This is wrong
2a == 1
3
4# This is also wrong
5if a = 1:
6    print("A is one")

Stop! Please take a moment to go back and carefully study the last two code examples. Save time later by making sure you understand when to use = and ==. Don’t guess.

10.4. Indentation

Indentation matters. Each line under the if statement that is indented will only be executed if the statement is True. In this example, the three lines indented under the if statement will run only if true, the fourth print statement will always run because it is not indented under an if statement.

1if a == 1:
2    print("If a is one, this will print.")
3    print("So will this.")
4    print("And this.")
5
6print("This will always print because it is not indented.")

The indentation amount must be the same. This wandering code doesn’t work.

1if a == 1:
2  print("Indented two spaces.")
3    print("Indented four. This will generate an error.")
4   print("The computer will want you to make up your mind.")

Once an if statement has been finished, it is not possible to re-indent to go back to it. The test has to be performed again. So this code example doesn’t work at all:

1if a == 1:
2    print("If a is one, this will print.")
3    print("So will this.")
4
5print("This will always print because it is not indented.")
6    print("This will generate an error. Why it is indented?")

If you try running it, you’ll get the following IndentationError:

  File "c:/my_code/test.py", line 8
    print("This will generate an error. Why it is indented?")
    ^
IndentationError: unexpected indent

10.5. Using And/Or

An if statement can check multiple conditions by chaining together comparisons with and and or. These are also considered to be operators just like the + and - characters are. Go ahead and create a third variable c and try using these two new operators yourself.

Example if statements, using “and” and “or”
1# And
2if a < b and a < c:
3    print("a is less than b and c")
4
5# Non-exclusive or
6if a < b or a < c:
7    print("a is less than either b or c (or both)")

Hint

Repeat yourself please.

A common mistake is to omit a variable when checking it against multiple conditions. You cannot write if a < b or c. Neither will if a < b or < c work. The computer does not know what to check against the variable c. It will not assume to check it against a. You need the full if a < b or a < c for it to work correctly.

1# This is not correct
2if a < b or < c:
3    print("a is less than b and c")

10.6. Boolean Variables

Python supports Boolean variables. What are Boolean variables? Boolean variables can store a value of either True or False. Boolean algebra was developed by George Boole back in 1854, well before electronic computers. Yet his work forms the basis of how computer logic works. If only he knew how important his work would become!

An if statement needs an expression to evaluate to True or False. What may seem odd is that it does not actually need to do any comparisons if a variable already evaluates to True or False.

For example, in this code we set the variable a to True. Our if statement does’t need a comparison. If a is True it will execute the statement, if it is False it will not.

If statements and Boolean data types
1# Boolean data type. This is legal!
2a = True
3if a:
4    print("a is true")

Another operator we can use is the not operator. You can take any statement or boolean and flip between True/False. The statement if a runs if a is True, the statement if not a runs if the statement is False.

The not operator example 2
1# How to use the not function
2if not a:
3    print("a is false")

It is also possible to use Boolean variables with the and and or operators.

Using “and” with Boolean variables
1a = True
2b = False
3
4if a and b:
5    print("a and b are both true")

Attention

Who knew True/False could be hard?

It is also possible to assign a variable to the result of a comparison. In the code below, the variables a and b are compared. If they are equal, c will be True, otherwise c will be False.

Assigning values to Boolean data types
 1a = 3
 2b = 3
 3
 4# This next line is strange-looking, but legal.
 5# c will be true or false, depending if
 6# a and b are equal.
 7c = a == b
 8
 9# Prints value of c, in this case True
10print(c)

Hint

Zero means False. Everything else is True.

It is possible to create an if statement with a condition that does not evaluate to True or False. Because this is confusing, we don’t use this fact a lot, but it is important to understand how the computer handles these values when searching for problems. These two examples will run, and will cause the text to be printed out because the values in the if statement are non-zero:

1if 1:
2    print("1")
3if "A":
4    print("A")

The code below will not print out anything because the value in the if statement is zero. The value zero is treated as False. Any value other than zero (like 2, -1, 600, or even “Fred”) is considered True.

1if 0:
2    print("Zero")

10.7. The input Function

Rather than hard-coding values into our program, we can use the input function to ask the user to type something in. The input function is reasonably simple to use:

1temperature = input("What is the temperature in Fahrenheit? ")
2print("You said the temperature was " + temperature + ".")
../../_images/keyboard.svg

As a parameter to input, just give it text to use as a prompt. Whatever the user types in, is stored in the variable on the left.

Note that there is a question mark and a space at the end of that string. If you didn’t have this, what the user types in will run right up next to the prompt. That looks terrible. The user is tempted to type a space as the first part of their input, which complicates things for us later.

There’s one more thing we have to learn. We can’t take what the user types in and compare it to a number. This program:

1temperature = input("What is the temperature in Fahrenheit? ")
2if temperature > 90:
3    print("It is hot outside.")

…will fail with a TypeError:

TypeError: '>' not supported between instances of 'str' and 'int'

Whatever the user types in is stored as text. We also call text a “string” because to the computer it is just a string of characters. This is different than a number, and the computer does not know how to compare them.

Therefore, we need to convert the input into a number. We can do with with the int for integers. If we have floating point numbers, use the float function.

In this example we get the input, convert it to an integer, and then we can use it in an if statement.

1# Get input from the user
2temperature = input("What is the temperature in Fahrenheit? ")
3
4# Convert the input to an integer
5temperature = int(temperature)
6
7# Do our comparison
8if temperature > 90:
9    print("It is hot outside.")

You can chain the input and int functions on one line if you like, as shown here:

1# Get input from the user
2temperature = int(input("What is the temperature in Fahrenheit? "))
3
4# Do our comparison
5if temperature > 90:
6    print("It is hot outside.")

10.8. Else and Else If

So far, we’ve used simple if statements to run a block of code, or not run it. What if we want to select between two blocks of code? What if we want to run one of four different blocks? To do this, we need “else” and “else if” logic.

Let’s start with a simple if statement that prints if it is hot outside:

1temperature = int(input("What is the temperature in Fahrenheit? "))
2if temperature > 90:
3    print("It is hot outside")
4print("Done")

If the programmer wants code to be executed if it is not hot, she can use the else statement. As for indentation, notice how the else is lined up with the i in the if statement. Also notice how else is followed by a colon just like the if statement. Try running this code. The if statement will always run one of the two blocks, but never both.

Example if/else statement
1temperature = int(input("What is the temperature in Fahrenheit? "))
2if temperature > 90:
3    print("It is hot outside")
4else:
5    print("It is not hot outside")
6print("Done")

In the case of an if…else statement, one block of code will always be executed. The first block will be executed if the statement evaluates to True, the second block if it evaluates to False.

It is possible to chain several if statements together using the else…if statement. Python abbreviates this as elif. In this example we add a third possible combination using elif.

Example if/elif/else statement
1temperature = int(input("What is the temperature in Fahrenheit? "))
2if temperature > 90:
3    print("It is hot outside")
4elif temperature < 30:
5    print("It is cold outside")
6else:
7    print("It is not hot outside")
8print("Done")

In this next example, we’ve made a mistake. The program will output “It is hot outside” even if the user types in 120 degrees. Why? How can the code be fixed?

Example of improper ordering if/elif/else
 1temperature = int(input("What is the temperature in Fahrenheit? "))
 2if temperature > 90:
 3    print("It is hot outside")
 4elif temperature > 110:
 5    print("Oh man, you could fry eggs on the pavement!")
 6elif temperature < 30:
 7    print("It is cold outside")
 8else:
 9    print("It is ok outside")
10print("Done")

The computer doesn’t do a “best-fit”, it looks at the if statement in order. As 120 is greater than 90, it will run the first condition and skip the rest. To fix this code, we need to reorder it.

Example of improper ordering if/elif/else
 1temperature = int(input("What is the temperature in Fahrenheit? "))
 2if temperature > 110:
 3    print("Oh man, you could fry eggs on the pavement!")
 4elif temperature > 90:
 5    print("It is hot outside")
 6elif temperature < 30:
 7    print("It is cold outside")
 8else:
 9    print("It is ok outside")
10print("Done")

10.9. Text Comparisons

It is possible to use an if statement to check text, as shown in this example.

Case sensitive text comparison
1user_name = input("What is your name? ")
2if user_name == "Paul":
3    print("You have a nice name.")
4else:
5    print("Your name is ok.")

The prior example will only match if the user enters “Paul” with a capital P. It will not work if the user enters lower-case “paul” or upper-case “PAUL”.

A common mistake is to forget the quotes around the string being compared. In the example below, the computer will think that Paul is a variable that stores a value. It will flag an error because it has no idea what is stored in the variable Paul.

Incorrect comparison
1user_name = input("What is your name? ")
2if user_name == Paul: # This does not work because quotes are missing
3    print("You have a nice name.")
4else:
5    print("Your name is ok.")

10.9.1. Multiple Text Possibilities

When comparing a variable to multiple possible strings of text, it is important to remember that the comparison must include the variable. For example:

# This does not work! It will always be true
if user_name == "Paul" or "Mary":

Instead, the code should read like this:

# This does work
if user_name == "Paul" or user_name == "Mary":

Confusingly, the first example will run, but it will always trigger the if statement even if the name isn’t Paul or Mary. This is because for any value other than zero, the computer assumes to mean True. “Mary” isn’t zero. So to the computer “Mary” is the same thing as True and so it will run the code in the if statement.

10.9.2. Case-Insensitive Comparisons

If the program needs to match text, and we don’t care if it is upper or lower case, we need a case-insensitive comparison. The easiest way to do that is to convert everything to lower-case, then compare. This can be done with the lower() command.

Attention

Learn to be insensitive.

The example below will take whatever the user enters, convert it to lower-case, and then do the comparison. Important: Don’t convert to lower-case and compare it against a string that has uppercase! Then you’ll never match.

Case-insensitive text comparison
1user_name = input("What is your name? ")
2if user_name.lower() == "paul":
3    print("You have a nice name.")
4else:
5    print("Your name is ok.")

10.10. Review

With the introduction of if statements we’ve learned how to run code only if a condition is true. By adding in elif and else statements we can run one of multiple possible code blocks depending upon a condition.

We’ve learned that we write conditions using comparison operators like < and >. We’ve learned that == is the comparison operator for asking if two items are equal, while = is the assignment operator used to set a variable’s value. We can reverse logic using the not operator.

Finally, we were introduced to Boolean values, where variables can store True or False. The if statements can operate based on those values.

10.10.1. Example if Statements

The next set of example code below runs through all the concepts talked about earlier.

  1# Sample Python/Pygame Programs
  2# Simpson College Computer Science
  3# http://programarcadegames.com/
  4# http://simpson.edu/computer-science/
  5
  6# Explanation video: http://youtu.be/pDpNSck2aXQ
  7
  8# Variables used in the example if statements
  9a = 4
 10b = 5
 11c = 6
 12
 13# Basic comparisons
 14if a < b:
 15    print("a is less than b")
 16
 17if a > b:
 18    print("a is greater than than b")
 19
 20if a <= b:
 21    print("a is less than or equal to b")
 22
 23if a >= b:
 24    print("a is greater than or equal to b")
 25
 26# NOTE: It is very easy to mix when to use == and =.
 27# Use == if you are asking if they are equal, use =
 28# if you are assigning a value.
 29if a == b:
 30    print("a is equal to b")
 31
 32# Not equal
 33if a != b:
 34    print("a and b are not equal")
 35
 36# And
 37if a < b and a < c:
 38    print("a is less than b and c")
 39
 40# Non-exclusive or
 41if a < b or a < c:
 42    print("a is less than either a or b (or both)")
 43
 44
 45# Boolean data type. This is legal!
 46a = True
 47if a:
 48    print("a is true")
 49
 50if not a:
 51    print("a is false")
 52
 53a = True
 54b = False
 55
 56if a and b:
 57    print("a and b are both true")
 58
 59a = 3
 60b = 3
 61c = a == b
 62print(c)
 63
 64# These are also legal and will trigger as being true because
 65# the values are not zero:
 66if 1:
 67    print("1")
 68if "A":
 69    print("A")
 70
 71# This will not trigger as true because it is zero.
 72if 0:
 73    print("Zero")
 74
 75# Comparing variables to multiple values.
 76# The first if statement appears to work, but it will always
 77# trigger as true even if the variable a is not equal to b.
 78# This is because "b" by itself is considered true.
 79a = "c"
 80if a == "B" or "b":
 81    print("a is equal to b. Maybe.")
 82
 83# This is the proper way to do the if statement.
 84if a == "B" or a == "b":
 85    print("a is equal to b.")
 86
 87# Example 1: If statement
 88temperature = int(input("What is the temperature in Fahrenheit? "))
 89if temperature > 90:
 90    print("It is hot outside")
 91print("Done")
 92
 93# Example 2: Else statement
 94temperature = int(input("What is the temperature in Fahrenheit? "))
 95if temperature > 90:
 96    print("It is hot outside")
 97else:
 98    print("It is not hot outside")
 99print("Done")
100
101# Example 3: Else if statement
102temperature = int(input("What is the temperature in Fahrenheit? "))
103if temperature > 90:
104    print("It is hot outside")
105elif temperature < 30:
106    print("It is cold outside")
107else:
108    print("It is not hot outside")
109print("Done")
110
111# Example 4: Ordering of statements
112# Something with this is wrong. What?
113temperature = int(input("What is the temperature in Fahrenheit? "))
114if temperature > 90:
115    print("It is hot outside")
116elif temperature > 110:
117    print("Oh man, you could fry eggs on the pavement!")
118elif temperature < 30:
119    print("It is cold outside")
120else:
121    print("It is ok outside")
122print("Done")
123
124# Comparisons using string/text
125# The input statement will ask the user for input and put it in user_name.
126user_name = input("What is your name? ")
127if user_name == "Paul":
128    print("You have a nice name.")
129else:
130    print("Your name is ok.")

10.10.2. Online Coding Problems

Practice on-line by completing the first set of coding problems available here:

https://repl.it/community/classrooms/174286

All problems beginning with 03 can be done with the knowledge from this chapter.