Functions - Lakelands Computing

Title
Go to content
Functions
A function is a block of organised, reusable code that is used to perform a single, related action.  If your program needs to run the same bit of code multiple times then you want to use a function.

Python has lots of built in functions, such as print () and input() but you can make your own. All functions have ().

To create a function you need to define it. This example makes a simple function to say something is correct. It could be called in a quiz.

  • def correct ():
    • print ("Well Done. That is correct")

As you can see, to define the function we use def. You then give your function a name. All the code to run when the function is called is tabbed in underneath the def statement.

To run a function you need to call it. This is really simple.

  • correct()

When a function is called the program runs the bit of code in the function then returns back to the main code at the point it left it ( i.e. immediately after the function call)

Take a look at the trinket to see a basic quiz example with 2 functions and calls.
Please note - a function can not be called in the program before it has been defined. This may sound obvious but it is really important. You need to write your functions definitions first, then run your main code (where the functions are called) second. Most programmers side step this problem by making their main code a function too and just having a single call to start the first function as the last thing in their program. Take a look at the second trinket to see what this looks like - you can see all the functions, including the main function are defined first and the call to run it main() is the very last bit of code, but will be the first bit to be activated.
You will often want to use data in your functions from the main program, or another function, such as increasing a score in the quiz example . To do that you need to use parameters.
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content