Logic and Decisions#

In this lesson we’ll learn how programs make decisions and how you can write programs that respond to input in by running some statements and not others.

Making Decisions with if#

What if you wanted your code to do different things based on user input? For example, suppose you want to play a game that prints different things based on a choice. The if statement allows you to conditionally run Python statements. Here’s a diagram of an if statement:

The if Statment

The if statement conditionally runs instructions inside the body of the if statement. The code is only run if the condition evaluates to True. In other words, the print function in the picture may or may not run depending on the value of number. Let’s start by making a widget for input:

import ipywidgets
number_widget = ipywidgets.IntText(description="Pick a number:")
display(number_widget)

Now let’s use an if statment to tell us when we’ve guessed the right number:

if number_widget.value == 34: 
    print("That's right!")

Enter the example code and make sure the indentation matches perfectly!

Notice that you only see “That’s right!” when the number in the widget is 34. Try using the debugger and watch execution “hop over” the first print statement.

The condition in the if statement is number.value == 34. When the condition is True the statements in the body of the if are executed, when the condition is False the statements are skipped. You can have as many statements as you like inside an if statement, even other if statements.

The if Condition#

The statement that follows the if keyword will be evaluated to True or False. While you’re coding remember that the statement you write must be asking a question of some form. In the example above the code is asking “if number is equal to 34?” There are many forms a question can take but they all have one thing in common: They will result in a True or False value. Here’s a few examples of questions:

If number is less than or equal to 34

if number <= 34:

If number modulus 2 is equal to 0 (in other words if number is even)?

if (number % 2) == 0:

If course is equal to the string "Python Programming for Everyone"

if course == "Python Programming for Everyone":

If course has the word Python anywhere in it

if "Python" in course:

While your working on a program rembmer that you can print the conditional statement that you put in the if to see if what you get is True or False. For example:

print(number <= 34)

If what you get is not a boolean it probably means you’ve made a mistake somewhere.

if with else#

The else statement lets you run code when something is not true. An else can only be used in combination with an if. Together they let you run one alternative no matter if the condition is True or False. Here’s a diagram of the structure of an if/else pair.

code

When you have and if/else one of the alternatives will always be run depending on the condition. Let’s display our number widget to try with else:

display(number_widget)

Now enter this example:

if number_widget.value == 34:
    print("That's right!")
else:
    print("Guess again.")

Notice that no condition follows the else. Whatever is in the else body is only run when the if condition is False and so it doesn’t need any more information. Enter the example in the next cell:

Asking Multiple Questions with elif#

In our guessing game there are really three conditions that we care about:

  1. The guess is correct

  2. The guess is too low

  3. The guess is too high

Using if and else we’ve captured only two condtions: right and wrong. There’s more we can do. When a program has to respond to a question with more than two alternatives the elif statement allows us to ask another question. The elif is short for “else if” and must follow an initial if statement and will only be run if the initial condition is False.

Let’s again display our number widget:

display(number_widget)

This example shows the best version of our game so far:

if number_widget.value == 34:
    print("That's right!")
elif number_widget.value < 34:
    print("Too low!")
else:
    print("Too high!")

Enter this version of the game and try it:

Here are the rules to remember when you construct if, elif, and else statements:

  1. They always start with if

  2. elif is optional and you can have as many as you like.

  3. else is optional but it can only be at the end.

  4. In an if, elif, else structure only one alternative will execute.

Let’s finish off the game program by testing if the user entered a number between 1 and 100 like we asked:

if number_widget.value == 34:
    print("That's right!")
elif number_widget.value < 1 or number_widget.value > 100:
    print("Bad guess.")
elif number_widget.value < 34:
    print("Too low!")
else:
    print("Too high!")

Let’s display our number box:

display(number_widget)

Enter the example into the next cell.

Order matters! Try reversing the two elif conditions in your code. What happens?

Logic#

Computers are machines that are built on their ability to perform logic. Logic functions are the basis of all mathematical computations and is built on three fundamental operations:

  • and

  • or

  • not

Logic operations use True and False as input, rather than numbers. Logic operations are defined by truth tables. Truth tables show the output of a logic operation given all combinations of input. The next sections will define the three fundamental logic operations.

The and Operator#

The and operator returns True when both inputs are True, otherwise it returns False. The truth table for and is:

Input A

Input B

Output

False

False

False

False

True

False

True

False

False

True

True

True

Use the cell below to test out the and operator:

False and False

The or Operator#

The or operator returns True if either input is True and False when both inputs are False. The truth table for or is:

Input A

Input B

Output

False

False

False

False

True

True

True

False

True

True

True

True

Use the cell below to test out the or operator:

False or False

The not Operator#

The not operator returns the opposite of its input. Unlike and and or, not only takes a single argument. The truth table for not is:

Input

Output

False

True

True

False

Use the cell below to test the not operator:

not True

Using Logic#

In Lesson 4 you learned operations that returned True and False. Those operations are:

  • == Equals

  • < Less than

  • <= Less than or equal to

  • > Greater than

  • >= Greater than or equal to

  • != Not equal to

The logical operators make it possible to combine operations to make compound questions.