How do I use functions in a menu system?
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
In one of our other articles we created a basic menu system for a game.
While this is a perfectly reasonable menu system it could lead to lots of unnecessary code and it will be difficult to read our code.
To avoid this issue we can use something called functions (or you might have heard them called procedures) .
Functions allow us to put separate blocks of code in their own sections and separate them so it is not all together.
For example each of our menu options could go to a different piece of code that is in its own function.
First we need to define our functions and put the code we need into them which looks like this:
Our Python code for these blocks of code looks like this:
If we add all of our different menu options into functions and add the whole menu into a function we end up with this:
If we ran this code in Python it would not run however. The reason is that Functions will only run when you tell them to and in this code we have not told the menu function to run. We need to call the menu function by adding the menu block at the end:
So you now have a working menu system using functions.