This is a complete diagram of how you define a function in Python π
To define a function in Python you need two main parts:
- the header
- the body
The header gives defines how the function is called and the arguments it needs.
The body is the code that does stuff.
The header starts with the keyword `def`, which is how Python π knows we are about to define a function.
Then, we have the function name, which should be descriptive.
After that, we have the list of parameters.
After the list of parameters, a colon.
The list of parameters starts and ends respectively with ( & ).
Between the parens, you write a comma-separated list of parameters.
The parameters are the data your function receives.
The parameter list can be empty, in which case you just have `():` next to the function name.
The function body is indented once with respect to the header and contains the code that runs when the function is called.
Before the body, it is customary to see a docstring, a comment that describes the function.
Your IDE will show you the docstring when you use the function.
Functions typically have return statments.
Return statements signal the end of the function & the data that comes off of the function.
If your function computes some result, you probably will use a return statement to give it back to the function user.
This was the gist of how you define a function in Python π
Did I forget anything? Let me know π
If you liked this short thread, follow me @mathsppblog.
I'm helping you take your Python π skills to the next level π
TL;DR:
A function definition has:
- its defining keyword
- the function name
- a (possibly empty) parameter list
- a colon to start the body
- a docstring with a function description
- the function body to do stuff
- a return statement to give results back
β’ β’ β’
Missing some Tweet in this thread? You can try to
force a refresh