FunctionsΒΆ
- In Python, a function is a named sequence of statements that belong together.
- Their primary purpose is to help us organize programs into chunks that match how we think about the problem.
The syntax for a function definition is:
def NAME( PARAMETERS ): STATEMENTS
- We can’t use a name that is a Python keyword, and the names must follow the rules for legal identifiers.
- There can be any number of statements inside the function, but they have to be indented from the
def
. - Function definitions are compound statements we will see, all have the same pattern:
- A header line which begins with a keyword and ends with a colon.
- 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 keyword in the header is
def
, which is followed by the name of the function and some parameters enclosed in parentheses. - The parameter list may be empty, or it may contain parameters separated by commas.
- In the definition, the parameter list is more specifically known as the formal parameters.
- When you use a function, you provide values to the formal parameters.
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.
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.
Here is a program containing a function to capture this idea. Give it a try.
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.
- Defining a new function does not make the function run. To do that we need a function call, i.e. a function invocation.
- We’ve already seen how to call some built-in functions like
print
,range
andint
. - Function calls contain the name of the function to be executed followed by a list of values, called arguments, which are assigned to the parameters in the function definition.