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.

Here’s a practical example of a guessing game:

number = int(input("Pick a number between 1 and 100: "))
if number == 34:
    print("That's right!")
print("Game Over")

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

[ ]:

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

The condition in the if statement is number == 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.

Nesting if Statements

A question I get a lot is, “Can I put this inside of an if statment?” The answer is YES! Absolutely any legal Python statement can go inside of an if statement. That’s a lot of power. At first it might be a bit confusing. Here’s an example of the guessing game that gives you a hint:

number = int(input("Pick a number between 1 and 100: "))
if number != 34:
    if number < 34:
        print("Too low!")
    if number > 34:
        print("Too high!")
if number == 34:
    print("That's right!")
print("Game Over")

Take a minute to type that version of the game into the next cell:

[ ]:

Try different values and use the debugger.

if and 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 what the condition is. 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.

Here’s an example of the guessing game using an else:

number = int(input("Pick a number between 1 and 100: "))
if number == 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:

[ ]:

Here’s the game again that gives a hint:

number = int(input("Pick a number between 1 and 100: "))
if number == 34:
    print("That's right!")
else:
    if number < 34:
        print("Too low!")
    else:
        print("Too high!")

Enter the code into the next cell:

[ ]:

Notice that you don’t need to test for ``number > 34``. Why?

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 been able to simplify the code a bit but 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. Here’s the best version of the guessing game so far:

number = int(input("Pick a number between 1 and 100: "))
if number == 34:
    print("That's right!")
elif number < 34:
    print("Too low!")
else:
    print("Too high!")

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

  1. They must start with if

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

  3. else is optional and must 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:

number = int(input("Pick a number between 1 and 100: "))
if number == 34:
    print("That's right!")
elif number < 1 or number > 100:
    print("Bad guess.")
elif number < 34:
    print("Too low!")
else:
    print("Too high!")

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. For example:

order = input("Would you like soup or salad?")
if order == 'soup' or order == 'salad':
    print("Okay!")
else:
    print("Huh?")

Enter this program that takes your order:

[ ]:

Do you follow the logic?