< Prev  |  Home  |  Next >

Python ‘elif’

Using an if/else statement is great for two choices, for example:

But what if there are more than 2 options? Sometimes, like in this case, more than 2 options doesn’t make sense; the password is either correct or it isn’t. But what about, say, entering a choice on a vending machine?

In the design for a vending machine program, I’m going use pseudocode as an alternative to a flowchart. pseudo means ‘like’, so pseudocode means ‘like code’. Here’s the design for a vending machine:

repeat forever:
   get the choice from the user
   if choice is 'a', give them an apple pie
   otherwise, if choice is 'b', give them an orange juice
   otherwise if choice is 'c', give them a sausage roll
   otherwise say 'invalid option'

As you can see, our design is sort of like Python code, but without worrying about the exact words and symbols used. I like using pseudocode, because these can become our comments in our Python program:

This then makes writing our program easy:

So we can use ‘elif’ to allow multiple ‘choices’. Notice how the last option just uses the ‘else’ command. If none of the other options are True, then the last ‘else’ is True, and it prints that the option is invalid. Let’s see how it works:

Choice Expected Actual
'A' Apple Pie Apple Pie
'a' Apple Pie Apple Pie
'B' Orange Juice Orange Juice
'dqw' Invalid option Invalid option


Design, code and test BOB V3. This version will accept and respond to various phrases, like “How are you?”, “Are you happy?” and “Goodbye?” etc.. See if you can make BOB have a (very basic) conversation with the user.

< Prev  |  Home  |  Next >