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

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

The following code should define a procedure that draws a triangle, but it may be mixed up <i>and may contain extra (unused) code</i>. Drag the needed code to the right side in the correct order. <b>Remember that the statements in the procedure must be indented!</b> To indent a block drag it further right.

You have attempted of activities on this page