How do I make a menu system in Python Blocks?
How Can We Help?
Teacher,
Cat enthusiast
- The 2022 End of Year Website Update - 01/01/2023
- Celebrating Ada Lovelace day - 10/10/2022
- Website update 5/9/22 - 05/09/2022
A very common feature of programs and games is a menu system. The menu system will allow users to choose different options such as starting a new game or loading a particular program or part of a program. Here we break down how to create a menu system for a fictional game called Time Chasers.
Starting our menu
First we need to decide what our menu needs to offer. For our Time Chasers game we are need the following options:
- Start a new game
- Load a game
- Options
- Credits
- Exit
Let’s print these options on to the screen.
The generated Python code looks like this:
So far so good. The user can see what options they have on the screen. They now need to be able to choose an option. We need to get them to input a response.
Select a menu option
We know that to get a user to input something we need to use the input block and store their answer as a variable. So let’s add an input block. Let’s call the variable “menuoption” and type in a suitable prompt to the user “Type in the menu option you would like”
Our Python code now looks like this:
So we have printed our menu options to the screen and asked the user to input which option they would like. We have then stored their response as a variable called menuoption.
So far so good but what will the user actually type in if they want to Start a new game? Start? Start a new game? Start game? Let’s simplify what the user needs to enter by numbering our menu options and asking them to choose the number of the menu option they would like:
Our Python code now looks like this:
Processing the users input
So we now have a menu system that displays to the user and we’ve made it nice and simple by making the user enter a number for the menu option they want. What do we do now?
We need to figure out what the user has chosen and run the correct code for the option.
We can do this using an if statement on our variable.
EG if the user typed in 1
run the start game code.
To do this we need to use an if statement. We also need to expand our if statement to include our other options using ‘if else’ or elif. Our finished if statement should look a bit like this:
Our Python code now looks like this:
So we have created a basic Python menu system but we can improve it further using something called functions. Take a look at how functions work and try it or go on to the next part – How do I use functions in a menu system?