13.4. 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

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.

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?

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

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.

Show Comments


Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page