Naming Sets of Steps

How did abs and int get defined? By defining new procedures and functions, we can associate a name with a sequence of steps. Look at the program below. What do you think it will do when you press the Run button? Click Run and see what happens.

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 turtle as input. If we want to actually execute the program we need to create a turtle and call the procedure as shown in the next example.

In the above program, we DEFine the word square to represent the Python statements that draw a square with a turtle. The square procedure takes as input a turtle that will be used to draw the square. Notice that the sequence of statements that are part of the square procedure are indented. Python uses indention to show what statements belong to the procedure. When the indention stops with from turtle import * it means that the new statements are not part of the procedure.

Note

Notice that we defined the turtle procedure def square(turtle): in the code above before we tried to call it square(malik). This is required in Python, but not in some other programming languages.

Defining a Function

You define a function just like you define a procedure, but it will also return a value as shown below.

Note

To return a value from a function use the Python keyword return followed by the value to return.

Check Your Understanding

    csp-6-3-1: Is abs a procedure or a function?
  • Procedure
  • It returns a value so it is a function
  • Function
  • It returns a value so it can't be a procedure
    csp-6-3-2: Is square a procedure or a function?
  • Procedure
  • It doesn't return a value so it is a procedure
  • Function
  • It doesn't return a value so it can't be a function

See the video below for a hint on how to solve the next mixed up code problem.

        csp-6-3-4: csp-6-3-3: The following code should define a procedure that draws a triangle, but it may be mixed up and may contain extra (unused) code.  Drag the needed code to the right side in the correct order.  Remember that the statements in the procedure must be indented!  To indent a block drag it further right.def triangle(turtle):
---
    turtle.left(60)
    turtle.forward(100)
    turtle.right(120)
    turtle.forward(100)
    turtle.right(120)
    turtle.forward(100)
    turtle.right(120)
---
    endDef #distractor
        
Next Section - Naming Input