Functions
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
The advantage of using functions is that it makes your code reusable.
In Python a function is defined (created) using the def keyword:
To call a function, use the function name followed by parenthesis:
In python, the function must be defined before you try to call it.
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (name). When the function is called, we pass along a first name, which is used inside the function to print the full name:
Return Values
To let a function return a value, use the return
statement:
Drawing Using Functions
If we want to use a function to draw using the turtle, we must pass the turtle to the function as one of the arguments:
Modify your game code so that the perimeter and box are drawn using functions
Last updated