Functions
Introduction to functions in Python.
A function is a block of organised, reusable code that is used to perform a single, related action.
Very similar to the functions you came across in maths, they take an input and return an output.
However, not every function has to take an input. Similarly, not every function has to return something. Some functions can even take multiple inputs!
An example you've already seen is the print()
function.
Functions improve code readability and code re-usability! They're super important to be familiar with as you become a better programmer.
Instead of:
You can do:
The output of this program will be 9 and 35.
But let's say you don't want to print the result, you just want to return it as data from the function. That's fine too! Here, you can use the return
statement in the function to return the data:
This program does the same as before, outputting 9, except using the return
statement instead of outputting from inside the function.
Last updated