Function Creation
Learn how to create and use functions in Python.
Structure
How do we actually make a function? In Python, a function can be defined using the def
keyword in the following format:
The
function name
is simply the name we’ll use to identify the function and call it inside our code. The naming best practices are similar to those we discussed for variable naming in previous lessons—use , avoidsnake_case Use lowercase characters and separate words using underscores. , avoiduncommon abbreviations Abbreviations that are not widely used are called uncommon abbreviations. For example, 'cfm' stands for 'cubic feet per minute, , and start function names with a verb that corresponds to the action performed by the function.special characters Special characters are symbols that are not letters or digits, used for various purposes; for example, @ in email addresses or # in hashtags. sort_list
andcalculate_area
are good examples of function naming.The
parameters
of a function are the inputs for that function. They are variables and can be used within their function block similar to how variables are used. Parameters are optional.The body of the function contains the set of operations that the function will perform. This is always indented to the right. Similar to how we indented the code belonging to an
if
block.
Implementation
Let’s start by making a plain function that prints four lines of text. It won’t have any parameters. We’ll name it ...