Functions

print is a function. Being a function it takes some arguments and runs operations with them.

Let’s see why do we need functions. The simple answer is to write less code, and to make it easier for us to think when we use it. We call this reusability.

We want for whatever reason to double numbers and add 1 then multiply with 7. We should do this for many numbers.

x = 10
y = 20
x = x * 2
x = x + 1
x = x * 7
y = y * 2
y = y + 1
y = y * 7

We can do this much better using parenthesis:

x = 10
y = 20
x = ((x*2)+1)*7
y = ((y*2)+1)*7

It still takes us a lot to write it. It would be annoying to have to do this for a lot of numbers.

The solution:

x = 10
y = 20
x = f(x)
y = f(y)

f is our function. If you run the above code you will get an error because we did not define f. To define it we use the def keyword:

def f(a):
	result = ((a*2)+1)*7
	return result

This means: take something (a) and do the wanted operations and save the result. Then, return the result. We can write it even shorter:

def f(a):
	return ((a*2)+1)*7