Question
How do I write a function and a return?
Solution
The basic syntax of a function can be seen below:
def function_name(optional_parameters):
# Code MUST be indented 2 spaces to be inside of the function
return value_to_be_returned
If you were to replace the generic names in the example above, you’d have a working function! There are some key things to notice here:
def
- this word must be there, but only when you’re defining the function, there’s no need to write it when you call a function.
function_name
- this is where you write the name of your function.
(optional_parameters)
- here you write parameter names that you can give values when you use your function by passing arguments.
:
- don’t forget the colon at the end of this line!
Inside the function, your code needs to be indented with 2 spaces to be considered part of the function’s code. Otherwise your code will be outside of the function!
return
- anything after this word on this line will be returned and the function will exit immediately. Nothing runs in a function after a return is executed!
value_to_be_returned
- replace this with whatever you intend for your function to return