Skip to main content

Section 17.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 procedure or function associates 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:
def ProcedureName(Input1, Input2, Input3, ...):
    Instruction1
    Instruction2
    ...
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 and then keep reading:
Why didn’t the Run button do anything? It is because the program defined the procedure square, but it never actually told Python to do the square procedure!

Warning 17.3.1.

Defining a procedure or function tells Python HOW to do a particular job. It does NOT tell Python to do the job. To do the procedure or function, we must call it.
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:

Checkpoint 17.3.2.

    Given the definition of the square function above, which is the correct way to make a square using a turtle lilly ?
  • square(lilly)
  • Correct.
  • lilly.square(turtleName)
  • Square is a standalone function. We do not call it using dot notation.
  • lilly.square()
  • Square is a standalone function. We do not call it using dot notation.
  • square(turtleName)
  • When we call this function, we need to give it a particular turtle as its input. lilly is the name of the turtle we want to use.
You have attempted of activities on this page.