functions and arguments

Functions

The structure of a function is:

def my_function_1(my_variable_1,my_variable_2):
    result = my_variable_1+my_variable_2
    return result

Where my_function_1 is the function, and my_variable_1 and my_variable_2 are the “arguments”. You can define a function by running

There are a couple things to note: first, the function is declared using the def keyword. This tells python to expect a function declaration. You then give the name, all the variables inside a set of parehtheses, finished by a colon. Everything inside the function after that must be indented.

Finally, you see the result keyword being used to return a calculated value. This does not need to be on its own line, and is completely optional. If you are setting a value to the result of whatever this function runs, however, return tells Python what value to return at the conclusion of this function.

You then “call” the function by running the function with two inputs supplied:

my_function_1(0,0)
0

You can use variables or literals when calling a function, and may set a value with whatever the function returns, as well

variable_1 = 1
result = my_function_1(variable_1,2)
print(result)
3

Arguments

There are two main types of variables you can supply to python functions: arguments and keyword arguments. my_function_1 is an example of what a function looks like with only arguments. Keyword arguments can be used instead. These supply a default value to the function, and are thus optional.

def my_function_2(my_kw_argument_1=0,my_kw_argument_2=0):
    result = my_kw_argument_1*my_kw_argument_2
    return result

Now, when calling my_function_2, you don’t need to supply any variables, if your use-case doesn’t need it.

my_function_2()
0

But you still can…with literals or variables

my_var_2 = 45
my_function_2(2,my_var_2)
90