FunctionsΒΆ

The syntax for a function definition is:

def NAME( PARAMETERS ):
    STATEMENTS
  1. A header line which begins with a keyword and ends with a colon.
  2. A body consisting of one or more Python statements, each indented the same amount from the header line.

We’ve already seen the for loop which follows this pattern.

The figure below shows this relationship. A function needs certain information to do its work. These values, often called arguments or actual parameters, are passed to the function by the user.

../_images/blackboxproc.png

This type of diagram is often called a black-box diagram because it only states the requirements from the perspective of the user. The user must know the name of the function and what arguments need to be passed. The details of how the function works are hidden inside the “black-box”.

Suppose we’re working with turtles and a common operation we need is to draw squares.

../_images/turtleproc.png

Here is a program containing a function to capture this idea. Give it a try.




(ch04_1)

This function is named drawSquare. It has two parameters — one to tell the function which turtle to move around and the other to tell it the size of the square we want drawn.

docstrings

If the first thing after the function header is a string, it is treated as a docstring and gets special treatment in Python and in some programming tools. For example, when we type a built-in function name with an unclosed parenthesis in PyScripter, a tooltip pops up, telling us what arguments the function takes, and it shows us any other text contained in the docstring.




(ch04_1a)

Next Section - Functions that Return Values