5.3. Defining Procedures - How¶
How does Python know what to do when we call functions like
abs or procedures like
alex.forward(50)? Someone had to define them. Defining a new procedures or
function, associates a name with a name with a sequence of steps.
In Python, we define a new procedure or function with the keyword
def. To use def, we also need
to specify: a name for the procedure, a list of its inputs, and the instructions the procedure will
perform in this format:
1def ProcedureName(Input1, Input2, Input3, ...): 2 Instruction1 3 Instruction2 4 ...
Key things to pay attention to:
The procedure name should obey the same rules as other names. Both syntax rules (no spaces or odd characters) and style conventions (camelCase or snake_case). Like other names, it should be meaningful - it should describe what task it performs.
The inputs (called parameters) are always inside ()
There may be multiple inputs - if there are, they are separated by commas. There may also be just one input or even no inputs.
There is a : after the input list.
The instructions that are part of the procedure or function are indented. These instructions are known as the function’s body.
Here is a definition for the
square procedure we tried to use on the last page. The square
procedure takes one input (called
turtleName). It has 8 instructions in its body. Try running
this code sample:
If you are wondering why the Run button didn’t seem to do anything, all that the program did
was define the procedure
square which takes a
turtleName as input. The code never actually
told Python to actually do the square procedure!
Remember - defining a procedure or function tells Python HOW to do a particular job. It does NOT tell Python to actually do the job. To do the procdeure or function, we must call the procedure.
We call a procedure by using its name, and then giving it the right number of inputs. Our
function requires one input - the name of the turtle that should make a square - so when we call
we must provide the name of a turtle.
This code sample defines our function, creates a turtle, and then calls the square function and gives it our turtle as input: