Parameters

To pass data into a function you use parameters. There are two stages to passing data into a function using a parameter:

  1. You define the function with a variable or list of variables inside the brackets after the function name.

    python3 def my_function(number): squared_number = number * number

  2. You call the function by passing a value or a variable of the same type (it doesn't have to have the same name) into the function.

1
2
3
4
5
def main():
    my_function(6)
    #or
    num = 6
    my_function(num)

This is great for getting data into the function so that you can use it. Once you have used it and changed it you need to know how to get it out again!!

Returning data from a function

To get data out of your function you use the return statement. Again, there are two stages to this:

  1. At the bottom of your function, write return followed by the variable name that has the value you want to return. This can be several variable names with commas in between:
1
2
3
def my_function(number):
    squared_number = number * number
    return squared_number
  1. This is the slightly tricky bit. When you call a function with a return statement in it, you need to put the value it is returning into a variable. You do this by putting the function at the right hand side of the equals and putting the variable that the return value will go into on the left.
1
2
3
4
5
def main():
    answer = my_function(6)
    #or
    num = 6
    answer = my_function(num)