Click to see the rest of the programming section :
As you move through your lessons on programming you will find that you use more subroutines (procedures & functions) to save yourself time. As programmers it means we write fewer lines of code, which is brilliant but it also saves the computer time and effort too.
The great thing about a subroutine is that the computer doesn’t have to assign any memory to it until the program uses the code, and when the subroutine is over any memory that was used is recycled freeing up the space for something else.
At GCSE we study procedural programming and so the only two subroutine types that we need to be concerned about are procedures and functions. All subroutines are a block of code that has a name and sits outside of the main program – functions use this technique to process something and send a value back.
Functions are particularly good for calculations that you need to repeat and validation of your user’s input. In the following example, we will assume that we have already written the menu procedure in the previous section. Our function pseudocode would look something like:
allowedMenu = [‘Deutsch’, “English”, “Espanol”]
choice = INPUT
WHILE choice is NOT IN allowedMenu DO
OUTPUT “Not a Valid Choice”
choice = INPUT
In this case, we’ve added a WHILE loop that insists that the user makes a valid choice before their choice is sent back to my program. A function is particularly good in this case because we can write our validation code once and call it many times throughout the program and because it will send a value back we can rest assured that the variables won’t hold any dodgy values!
Let’s see what this looks like in Python when we combine the function with the procedure that we created in the previous section. In the example code below, the new function is used to make sure that the user enters a valid input – in this case, a string that exists within the array.
Try expanding the code so that once the user selects a language, they can translate a word using the example code that we saw in Use of Records for Saving Data. To run the program in the browser, press Ctrl + Enter.
Find this page helpful? Share the love on your social media mentioning @TeachAllAboutIT and we’ll enter you in our monthly draw to win a gift voucher for any product on the site!