Using elif for more options

We have used if and else to handle two possible options, but what could you do for if you want more than two options? What if you want to test if a value is negative, 0, or positive? One way to do this using multiple if statements is shown below.

Run this several times and change the value of x each time. Try it with a positive number, a negative number, and 0 to check that it works correctly. Modify the code to take a number as input from the user instead.

Another way to choose between three options is to use if followed by elif and finally else as shown below.

Which way is better? It turns out that beginners have an easier time understanding 3 if statements. Experts prefer using if, elif, and else since it takes less time to execute and makes it less likely that you will miss a value.

Mixed up programs

        csp-13-4-2: csp-13-4-1: The following program should report which team won or if there was a tie.
But the code has been mixed up.  Drag it into the right order with the right
indention.team1 = 20
team2 = 20
---
if (team1 > team2):
    print("team1 won")
---
elif (team2 > team1):
---
    print("team2 won")
---
else:
---
    print("team1 and team2 tied")
        

You can use as many elif statements as you need. You can only have one else statement. What if you have scaled some data from 0 to 1 and want to know what quartile a value is in?

    csp-13-4-3: What would be printed if you moved lines 6-7 before lines 4-5 and set x equal to .5?
  • x is in the first quartile - x <= .25
  • This will only print if x is less then or equal to .25.
  • x is in the second quartile - .25 < x <= .5
  • This will print if the other if's were not true, and if x is less than or equal to .5. By moving lines 6-7 before lines 4-5 this will never print.
  • x is in the third quartile - .5 < x <= .75
  • This will print if the other if's are not true and if x is less than or equal to .75. So, moving lines 6-7 before lines 4-5 messes up what this code is intended to do and incorrectly prints that .5 is in the third quartile.
  • x is in the fourth quartile - .75 < x <= 1
  • This will only print if all of the other if's were false.

Here’s the fortune teller code from before but now it is written using elif and else instead of just if.

    csp-13-4-4: How many conditions (logical expressions) are checked in the code above if the user answered 2?
  • 1
  • It will have to test if num is equal to 1 and because that is false it will test if num is equal to 2.
  • 2
  • With the elif it won't execute the other elif's if one of them is true.
  • 5
  • With elif it will test each until one of the conditions is true and then skip the rest.
  • 6
  • There are only 5 logical expression here so it can't be more than 5.

Write code to that will take a number as input and return a response as a string. Ask the user to enter the number of states visited in the US. Have 3 categories of responses.

Next Section - Chapter 13 - Summary