Professional Documents
Culture Documents
Functions
Functions
Intro
• De ning Functions
• Variable Scope
• Documentation
• Lambda Expressions
• Iterators and Generators
You can think about functions as a way to take what you have
already learned how to do, and put it in a holder that allows you
to use it over and over again in an easy to use container.
De ning Functions
Example of a function de nition:
cylinder_volume(10, 3)
This is called a function call statement.
Function Header
Let's start with the function header, which is the rst line of a
function de nition.
1
fi
fi
fi
fi
fi
fi
fi
viernes, 10 de abril de 2020
1. The function header always starts with the def keyword, which indicates that
this is a function de nition.
2. Then comes the function name (here, cylinder_volume), which follows
the same naming conventions as variables. You can revisit the naming
conventions below.
3. Immediately after the name are parentheses that may
include arguments separated by commas (here, height and radius).
Arguments, or parameters, are values that are passed in as inputs when the
function is called, and are used in the function body. If a function doesn't take
arguments, these parentheses are left empty.
4. The header always end with a colon :.
Function Body
The rest of the function is contained in the body, which is where
the function does its work.
1. The body of a function is the code indented after the header line. Here, it's
the two lines that de ne pi and return the volume.
2. Within this body, we can refer to the argument variables and de ne new
variables, which can only be used within these indented lines.
3. The body will often include a return statement, which is used to send back
an output value from the function to the statement that called the function.
A return statement consists of the return keyword followed by an
expression that is evaluated to get the output value for the function. If there is
no return statement, the function simply returns None.
Default Arguments
We can add default arguments in a function to have default
values for parameters that are unspeci ed in a function call.
2
fi
fi
fi
fi
viernes, 10 de abril de 2020
3
viernes, 10 de abril de 2020