User menus
When we develop console-based applications (those that run in text interfaces), we usually want a nice, reliable way for users to interact with our application.
That user interface is what I call a "menu". For example, this might be an interface for a console-based application:
Welcome to the countries app.
You have visited 0 countries so far.
Enter 'a' to add a country you've visited, or 'q' to quit:
Imagine the user enters a
, then we might show something like this:
...
Enter 'a' to add a country you've visited, or 'q' to quit: a
Country name:
Date visited:
You have added (country name) to your list. You have visited 1 country.
Enter 'a' to add another country, 'l' to list the countries you've visited, or 'q' to quit:
That's an example of an interface. We'll be building this interface for the final project in this section!
Note the way the interface ends: the user can keep typing a
over an over again to add more and more countries. This is the perfect place for a loop!
For vs. while
Should you use a for
loop, or a while
loop in this situation?
For loops are best used when you want to go over a list of elements, so you must know what the list is before the loop starts.
While loops are best to run until a condition is False
.
In this case I think a while
loop is the better choice, because we don't know how many times the user will want to run our menu. Instead, we want to run until the user types q
.
This means we want the loop to run as long as the user's input is not q
.
We could define the main structure of our menu in this way:
print("Welcome to the countries app.")
print("You have visited 0 countries so far.")
user_input = input("Enter 'a' to add a country you've visited, or 'q' to quit: ")
while user_input != "q":
# Do stuff here
# At the end of the loop, ask the user whether they want to go again
user_input = input("Enter 'a' to add another country, 'l' to list the countries you've visited, or 'q' to quit: ")
The first time we ask the user for their input we don't tell them they can type l
, because at the start of the program they won't have any countries in their list!
I think you're ready to tackle this section's project. Bring it on!