# More Functions
Functions allow code to be executed without copying and pasting the same code in multiple places. Using functions means writing less code (and therefore potentially fewer mistakes) and makes the code more maintainable (if there is an error it only has to be fixed in the function and not in each place where the code is duplicated).
All functions have the following format:
def <function name>(<input_variable_1>, <input_variable_2>):
- 'def' tells the computer the following code is the start of a function definition
- <function name> is the name of the function. This name is used to execute the code in the function, also know as calling the function.
- <input_variable_1> is an input variable. They are optional. There can be no input variables or there can be several. If there is more than 1 input variable, they're separated by commas.
- '()' open and close parenthesis are always right after the function name. If there are any input variables they go between the parenthesis
- ':" the colon is always at the end, just like for, if, elif, and else
Any one of the input variables can have default values. These values are applied when the function is called without a value for the input variable. Once a default value is set for an input variable all other input variables that come afterwards must also have default values.
A function can return a value with the return keyword. When return is used,
the function ends immediately and no further lines of code are executed. The
returned value can be saved in a variable when the function is called: return_var = function_4(10)
To use a function write the function's name and put the same number of inputs
listed in the function definition. The inputs can either be a value like 1
,
20.5
, "text"
or a variable.
Now, you write a program with some functions. You should have a function to do each of these things:
Ask the user to enter the user's name, using
input()
. If the user enters no name, change the user's name to 'NoName'.Check if the user's name is "Bob" and if it is, print "Hi Bob!"
Call the first function to get the user's name, then call the second function to check it. Call the function using named parameters, like the way we called
function_2()
One of your functions should have a default parameter.