Defining functions with positional parameters
The essential Python function definition is built with the def
statement. We provide a name, the names of the parameters, and an indented suite of statements that is the body of the function. The return
statement provides the range of values.
The syntax looks like this:
def prod(sequence): p= 1 for item in sequence:p *= item return p
We've defined a name, prod
, and provided a list of only one parameter, sequence
. The body of the function includes three statements: assignment, for
, and return
. The expression in the return
statement provides the resulting value.
This fits the mathematical idea of a function reasonably well. The domain of values is any numeric sequence, the range will be a value of the a type which reflects the data types in the sequence.
We evaluate a function by simply using the name and a specific value for the argument in an expression:
>>> prod([1,2,3,4]) 24 >>> prod(range(1,6)) 120
In the first...