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:

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!

Warning

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 square function requires one input - the name of the turtle that should make a square - so when we call sqaure 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:

You have attempted of activities on this page