Conditional Processing

Jump To

Making Decisions Using if

The programs we have developed so far have been pretty simple, and all of them have followed a sequential path: first do one thing, then do another, and so forth. Most programs, however, will require some decision-making. We might want to do one thing if the user inputs a particular value, and another thing altogether if the user does not. To make decisions in Python, we use if statements.

if statements have the following form.

if <CONDITION>:
   <CODE TO BE EXECUTED>

After the if keyword, some condition must be specified to check against. A colon (:) follows this condition, and the code to be executed is indented. This is how Python organizes blocks of code. All code contained within a block is associated with the if statement.

Besides mathematics, one of the things that computers are good at is comparing values. For example, we might wish to compare two numbers to see if they have the same value. We cannot use the = operator to check if two values are equal, because = assigns a value to a variable. Instead we use two equal signs, ==, to check for equality. It might be easier to remember this by noting that “equal to” sounds the same as “equal two”.

num = int(input("Please enter a number: "))
if num == 5:
   print("You entered a five.")

Try running the code above. If you enter a 5, the program outputs a message. If any other value is entered, nothing is displayed.

It is possible to chain one if statement after another to handle multiple conditions.

number = int(input("Enter a number between 1 and 4: "))
if number == 1:
   print("ONE")
if number == 2:
   print("TWO")
if number == 3:
   print("THREE")
if number == 4:
   print("FOUR")

Run the code to verify that all cases work as expected. Note that if any value outside of the range 1-4 is entered, the program does not output a message.

In addition to ==, Python uses other comparison operators. For the following table, assume that x=10 and y=20.

Operator Description Example Result
== Equal to x == y False
!= Not equal to x != y True
> Greater than x > y False
< Less than x < y True
>= Greater than or equal to x >= y False
<= Less than or equal to x <= y True

The following code will output a congratulatory message for scoring a 70 or higher on a test, and an alternate message for scoring less than 70.

testScore = int(input("What did you score on your test? "))
if testScore >= 70:
   print("Good job!")
if testScore < 70:
   print("Better luck next time!")

When Python checks a variable against some condition, it determines whether the expression is true or false. Both keywords True and False are reserved words in Python, and cannot be used to name variables. A variable that assumes either a True or False value is called a boolean data type. In the code above, a value of 65 would cause the first if statement to be False, while the second would be True. Booleans are often used in programs to monitor whether conditions have been met or not.

One of the more common logical errors arises from incorrect ordering of test cases. Consider the following code.

temperature = int(input("Enter the temperature outside: "))
if temperature < 10:
   print("Chilly!")
if temperature < 0:
   print("Brrrr!")

If a value of 8 is entered, the program outputs Chilly! as expected; but when a value of -20 is entered, it still outputs Chilly!, which is not what we want. To fix this, reorder the if statements.

temperature = int(input("Enter the temperature outside: "))
if temperature < 0:
   print("Brrrr!")
if temperature < 10:
   print("Chilly!")

Since we are checking if a certain value is less than another, they should be ordered ascendingly, so that the lowest case gets executed first. Similarly, we could order the if statements descendingly if we wanted to check if a certain value is greater than another.

When running the above code, you should have noticed that a new error was introduced — both Brrr! and Chilly! were output. Again, this is probably not the desired behaviour of the program, but it is executing exactly as instructed. If a value -20 is entered, the program first compares -20 < 0, which is True, so it outputs Brrr! to the screen. It then moves on and compares -20 < 10, which is also True, so it outputs Chilly! as well. To prevent this from happening, we need to have a way of preventing the program from executing any subsequent if statements once one has evaluated to True. We will cover this in the very next section.

Exercises

  1. Determine the output of each program.
    1. x = 5
      if x <= 2:
         print("YES")
      if x > 5:
         print("NO")
      if x != 7:
         print("MAYBE")
      
    2. z = "a"
      if z != "A":
         print("YES")
      if z == "a":
         print("NO")
      
  2. Use if statements in programs to accomplish each task.
    1. Output "GREATER" if a given integer is greater than 50.
    2. Output "OTHER" if a given integer has any value other than 12.
    3. Output "HIGHER" if a given integer is higher than 10, "LOWER" if it is lower than 10, or "EQUAL" if equal to 10.
    4. Output "VOWEL" if a given uppercase letter is a vowel.
    5. Output "CONSONANT" if a given uppercase letter is a consonant.
    6. Output "OUTSIDE" if a given integer is outside of the range 5-25.

Alternative Decisions Using else and elif

In the previous section, we saw a situation in which two if statements evaluated to True, resulting in two messages being output to the screen. This was not the behaviour that we wanted. Ideally, we would like to see only one message displayed. To make this happen, we need to introduce a new command that executes only when a condition is not satisfied.

To indicate that a particular block of code should be executed when a condition in a previous if statement is not met, use an else statement. The code contained in the else block will not be executed unless the if block before it is False.

if <CONDITION>:
   <CODE TO BE EXECUTED>
else:
   <CODE TO BE EXECUTED>

Let's say we want to output a message based on whether the user enters the letter A or not. We might write the following code.

letter = input("Please enter a letter: ")
if letter == "A":
   print("You entered the letter A.")
else:
   print("You did not enter the letter A.")

The example above is pretty trivial, but illustrates exactly how else operates. If the user enters "A", the condition in the first if statement is True, so the first message is printed to the screen. If the user enters any other character, the condition in the first if statement is False, so the message contained in the else block is printed. What happens if the user enters "a" instead? Why does this happen?

The following code uses the modulus operator to determine if a given integer is divisible by 5.

number = int(input("Please enter an integer: "))
if number % 5 == 0:
   print(number, "is divisible by 5.")
else:
   print(number, "is not divisible by 5.")

Note that else does not depend on any conditions. Specifying conditions results in an error. Attempting to run the code below results in a syntax error.

x = 10
if x > 20:
    print(x, "is greater than 20.")
else x < 20:
    print(x, "is less than 20.")

Now, let's revisit the temperature code from the last section.

temperature = int(input("Enter the temperature outside: "))
if temperature < 0:
   print("Brrrr!")
if temperature < 10:
   print("Chilly!")

What we really want to do in this case is to evaluate one of the if statements, while ignoring the other. To do this, use the elif statement. elif is short for else if, and must follow an if block. An else statement may follow an elif block to handle all other cases. In this sense, else is sort of a "catch-all" condition.

if <CONDITION>:
   <CODE TO BE EXECUTED>
elif <CONDITION>:
   <CODE TO BE EXECUTED>
...
else:
   <CODE TO BE EXECUTED>

For example, the following code will print a particular message, depending on the user's age.

age = int(input("How old are you? "))
if age < 3:
   print("You're a baby!")
elif age < 13:
   print("You're a kid!")
elif age < 18:
   print("You're a teen!")
else:
   print("You're an adult!")

Note the ordering of the comparisons. If we had reversed the order and checked if age was less than 18 first, the program would not have worked as expected. If the user entered an age of 5, it would have triggered the if statement and printed You're a teen! instead. Remember — logical errors can be tricky to spot!

Try running the following code with various values for x and y to verify that it works correctly.

import math
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
if x // y >= 5:
   print(x, "is at least five times larger than", y)
elif x / y == 2:
   print(x, "is double", y)
elif x - y != 0:
   print("Both values are distinct")
else:
   print("Nothing to see here")

Exercises

  1. Correct the logical errors in each program so they work as expected, given proper input.
    1. # Check if a number is between 5 and 10
      num = int(input("Please enter a number: "))
      if num <= 10:
         print("Between 5 and 10.")
      elif num >= 5:
         print("Between 5 and 10.")
      else:
         print("Not between 5 and 10.")
      
    2. # Check if an integer is two digits long
      integer = int(input("Please enter a positive integer: "))
      if integer < 99:
         print("Two digits.")
      elif integer < 9:
         print("One digit.")
      
  2. Write programs to solve each problem.
    1. Given the user’s age, display a message indicating whether or not (s)he is old enough to drive.
    2. Given three numbers, determine if the third number is equal to the sum of the first two numbers.
    3. Given two numbers, indicate the larger of the two.
    4. Determine if a given integer is even or odd.
    5. Determine if an integer entered by the user is positive, negative, or neither.
    6. Determine the roots of a quadratic equation, , given the three coefficients.
    7. Compute and display a person's weekly salary as determined by the following rules:
      • For the first 40 hours, the person receives $12.00 per hour.
      • For each additional hour worked, the person receives $15.00 per hour.

Nesting if Statements

Recall that we can nest functions inside each other. For example, to read an integer from the user, we can place the input function inside of int as follows.

integer = int(input("Please enter an integer: "))

Similarly, if statements can be placed inside of other if blocks. The general format of nested if statements is something like this.

if <CONDITION>:
   if <CONDITION>:
      <CODE TO BE EXECUTED>:
   ...

For example, we can check if a given integers is between five and ten, inclusive, using the following code.

num = int(input("Enter a number: "))
if num >= 5:
   if num <= 10:
      print(num, "is between five and ten.")

It is also possible to nest else and elif statements. Cleaning up the code above, we might add a message for when the given integer is not between five and ten.

num = int(input("Enter a number: "))
if num >= 5:
   if num <= 10:
      print(num, "is between five and ten.")
   else:
      print(num, "is greater than ten.")
else:
   print(num, "is less than five.")

Note how Python uses indentation to associate each else statement with its corresponding if statement — the inner else goes with the inner if, while the outer else goes with the initial if.

Nested ifs can be used to check if a given letter is a consonant.

letter = input("Please enter an uppercase letter: ")
if letter != "A":
   if letter != "E":
      if letter != "I":
         if letter != "O":
            if letter != "U":
               print(letter, "is a consonant.")

Note that the same task could be accomplished using elif and else statements instead.

Now, let's say we are given a three-digit integer (100-999), and we want to know if it contains exactly two of the same digit. We might try writing the following code.

number = int(input("Please enter a three-digit number: "))
if number == 101:
   print(number, "has at least two digits the same.")
elif number == 110:
   print(number, "has at least two digits the same.")
elif number == 121:
   print(number, "has at least two digits the same.")
...
elif number == 999:
   print(number, "has at least two digits the same.")
else:
   print(number, "has three different digits.")

This is terribly innefficient code. There are 243 integers between 100 and 999 that contain exactly two of the same digit. Each of these would require a check. Yikes! A better solution is to alanlyze the various pairs of digits, and check if any two are equal. Using the // and % operators, we can "extract" each digit.

number = int(input("Please enter a three-digit integer: "))
firstDigit = number // 100
secondDigit = (number % 100) // 10
thirdDigit = number % 10
if firstDigit == secondDigit:
   if secondDigit == thirdDigit:
      print(number, "does not contain exactly two of the same digit.")
   else:
      print(number, "contains exactly two of the same digit.")
elif firstDigit == thirdDigit:
   print(number, "contains exactly two of the same digit.")
elif secondDigit == thirdDigit:
   print(number, "contains exactly two of the same digit.")
else:
   print(number, "does not contain exactly two of the same digit.")

To see why the extraction method above works, let's use 775 as an example. 100 divides cleanly into 775 seven times, so firstDigit is assigned a value of 7. Next, the remainder when 775 is divided by 100 is 75. 10 divides cleanly into 75 seven times, so secondDigit is assigned a value of 7. Finally, 775 has a remainder of 5 when divided by 10, so thirdDigit is assigned a value of 5.

The code then begins comparing possible pairs of digits. 7 and 7 are equal, so the first if statement is True. The first elif statement is False, since 7 and 5 are not equal. This makes the nested else statement True, and the appropriate message is displayed.

As a counter-example, 524 causes all of the if and elif statements to evaluate to False, so the final else is executed. Try using other values and following through the code by hand, to verify that the logic is accurate.

Exercises

  1. Write programs to solve each problem.
    1. Determine the discount percentage for selling a TV, using the following rules:
      • If plasma, discount will be 5% of selling price.
      • If LCD, discount is 8% of selling price for a 30" model, and 10% of selling price for 42" model.
    2. Prompt the user to select a triangle or a rectangle. If the user selects a triangle, read its base and height. If the user selects a rectangle, read its length and width. Calculate the area of the selected shape.
    3. Determine if a given year is a leap year. Leap years are divisible by 4, but not by 100, unless they are also divisible by 400.
    4. Display the largest of three integers entered by the user.
    5. Given a three-digit integer (100-999), convert it to text form. For example, 328 would read "three hundred and twenty eight".

Checking Multiple Conditions With and, or and not

We have seen how to chain together multiple if statements by nestin them. This works, but it hurts readability if too many conditions are nested. Sometimes we are looking for a way to link two or three conditions, whereby some must be True while others are False. Python uses the keywords and and or to link multiple conditions.

If two conditions are separated by or, an if block will execute if either condition is True or if both are True. In this sense, or is not exclusive. If so, only one condition could be True for the if block to execute. Two conditions separated by and must both be True for an if block to execute. For example, consider the sentence "if it is snowing and I am going outside, then I will wear my jacket." The jacket will only be worn if both conditions are met — there is no need to put it on if you are staying indoors, and no reason if it is not snowing.

The truth tables below show how or and and work.

a b a or b
True True True
True False True
False True True
False False False
a b a and b
True True True
True False False
False True False
False False False

The following code checks if a number is in the range 1-10 inclusive.

number = int(input("Please enter a number: "))
if number >= 1 and number <= 10:
   print(number, "is between 1 and 10.")
else:
   print(number, "is not between 1 and 10.")

To be between 1 and 10, the number must simultaneously be greater than 1 and less than 10. Any number that does not meet these criteria must fall outside of the specified range.

On the other hand, checking if a number is outside of a range can be done using or.

number = int(input("Please enter a number: "))
if number > 10 or number < 1:
   print(number, "is not between 1 and 10.")
else:
   print(number, "is between 1 and 10.")

Python also uses the not keyword to "invert" the truth of a condition. If a is True, then not(a) is False, and vice versa. Below is code to check if a number is between 1 and 10 inclusive, that uses not.

number = int(input("Please enter a number: "))
if not(number > 10) and not(number < 1):
   print(number, "is between 1 and 10.")
else:
   print(number, "is not between 1 and 10.")

A common logical error is to use and in place of or, or vice versa. The following code does not behave as expected. Try it and see.

number = int(input("Please enter a number: "))
if not(number > 10) or not(number < 1):
   print(number, "is between 1 and 10.")
else:
   print(number, "is not between 1 and 10.")

To be efficient, Python short-circuits its comparisons. Since an if statement is True once any single condition separated by ors is True, Python stops checking the rest of the conditions once. Similarly, since and requires all conditions to be True, then Python stops checking conditions once a condition separated by ands is False. Consider the following code.

x = 10
if x == 10 or y == 5:
    print("YES")
else:
    print("NO")

This code runs, even though y has not been defined, because the second condition is never checked. Since x is equal to 10, the first condition is true, and YES is printed to the screen. Try changing the value of x to see how the code generates an run-time error.

Exercises

  1. Write programs to accomplish each task.
    1. Print a message if the user enters an A, regardless of case.
    2. Determine if a given integer is divisible by either 3 or 5.
    3. Determine if a given integer is divisible by both 3 and 5.
    4. Determine if a given integer is not a multiple of 4 or 7.
    5. Determine if two given integers are both positive, both negative, or one positive and one negative.
    6. Read three integers and determine if any of the three is a multiple of the other two.
    7. Read three integers and determine if exactly two are greater than 10.
    8. Use two boolean values, a and b, to complete the two tables below.
      a b not(a and b)
      True True
      True False
      False True
      False False
      a b not(a) or not(b)
      True True
      True False
      False True
      False False
    9. Determine an equivalent expression for not(a or b), similar to the previous question. Use tables to verify your answer.

Additional Programs Using Conditional Processing

  1. Given three integers, determine the largest even integer entered. If no integer is even, display an error message. If the largest even integer occurs more than once, output a message indicating so.
  2. Given the names and birthdays of two people, determine which is older. Ensure that the user enters the year, month and day for each person's birthday.
  3. Given three integers, determine if they are in ascending (increasing) order, descending (decreasing) order, or out of order.

6 Responses to Conditional Processing

  1. B says:

    You need to put brackets on the first example. :P

  2. N says:

    I absolutely love your tutorial!

  3. L says:

    For the first example of the OR statement, the ‘num’ should be ‘number’.