Creating functions

--Originally published at Quirino´s Projects

This a little bit hard to catch for early beginners, but trust me these are really easy once you understand how the functions are made.

Sometimes we want to do something many or several times in our code changing only a number or a string, and repeating ourselves makes our program harder to read

keep-calm-and-don-t-repeat-yourself

This is were functions become our ally

If we wanted to get the factorial of 3 numbers, without functions we would need to do this:

num1 = int(input(“N: “))
result1 = 1
for i in range(1,num + 1):
result1 *= i
num2 = int(input(“N: “))
result2 = 1
for i in range(1,num2 + 1):
result2 *= i

num3 = int(input(“N: “))
result3 = 1
for i in range(1,num3 + 1):
result3 *= i

print (num1)

print(num2)

print (num3)

Using the for loop each time makes a bulky code, so instead we could use a function

def factorial(num):
result = 1
for i in range(1,num+1):
result *= i
return result

To explain how a function in python works we need to see each part

def

Stands for define is the keyword needed to tell python that the next thing will be a function

factorial

This is the name our function has and the name it will be called with it can be any name but there are a few conventions about naming things in python

Please Check https://www.python.org/dev/peps/pep-0008/

(num)

These are why functions are a bit hard at first, num is the argument that is passed to the function we defined just one, called num but a function can have as many arguments as we want, this argument is used locally inside the function and we cannot edit it outside the function block for easier understanding lets look at this code

def numberTimesThree(num):

    return

* 3

In the code above we have the num that is passed  to the function but when this function is called we can use any number

if we do:

print (numberTimesThree(3))

The 3 is passed to num and now num has the value of 3 and can be used inside our program

When we define a function the argument is not the variable that takes but how the variable will be called inside our program