# Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

The advantage of using functions is that it makes your code reusable.&#x20;

In Python a function is defined (created) using the def keyword:

```
def myFunction(): 
    print("Hello from a function")
```

To call a function, use the function name followed by parenthesis:

```
def myFunction():
  print("Hello from a function")

myFunction()
```

{% hint style="info" %}
In python, the function must be defined before you try to call it.
{% endhint %}

### Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (name). When the function is called, we pass along a first name, which is used inside the function to print the full name:

```
def myFunction(name):
  print(name + " is a human.")

myFunction("Emil")
myFunction("Tobias")
myFunction("Linus")
```

### Return Values

To let a function return a value, use the `return` statement:

```
def myFunction(x):
  return 5 * x

print(myFunction(3))
print(myFunction(5))
print(myFunction(9))
```

### Drawing Using Functions

If we want to use a function to draw using the turtle, we must pass the turtle to the function as one of the arguments:

```
import turtle
t=turtle.Pen()
t.speed(0)

def circle(t, r, x, y, color):
    t.pencolor(color)
    t.penup()
    t.goto(x, y)
    t.pendown()
    t.circle(r)

circle(t, 10, 100, 100, 'red')
circle(t, 100, -200, -200, 'blue')
circle(t, 50, -200, -200, 'green')

```

{% hint style="success" %}
Modify your game code so that the perimeter and box are drawn using functions
{% endhint %}
