When talking about functions we’re not actually talking about math functions per se, but pieces of code that can be reused in other parts of our scripts with variable inputs to apply the same set of actions. Just like with math functions we pass parameters to the function and get a result out of it.

Before we go into how functions work in python let’s take a look at the basic arithmetic operations and how they are used in Python

 # Let's define a couple of number variables number1 = 12 number2 = 23 # Sum number1 + number2 # Result: 35 # Substraction number1 - number2 # Result: -11 # Multiplication number1 * number2 # Result: 276 # Division number1 / number2 # Result: 0.5217391304347826

Python functions⌗

In python we can define a function that might or might not receive any arguments, but as a general rule of thumb (and Python guidelines) you should always return a value to indicate the end of a function. The general syntax for a function is:

 def function_name(args): #Do something here somevalue = 'something' return somevalue

For now we will define four different functions, one for each of the basic arithmetic operations, and they will all accept two arguments

 def sum(num1, num2): return num1 + num2 def substract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2

After the functions have been defined we can use them anywhere else in our code with any values for the arguments, we don’t actually need to define those values beforehand.

 sum(189,12) # Result: 201 substract(238,23) # Result: 215 multiply(123,123) # Result: 15129 divide(12234,12) # Result: 1019.5

Of course we are assuming that the user will input numbers in the arguments, if other types of values are entered then Python will throw and error and the script won’t run, to avoid this we can do some kind of value sanitization but we’re not going to touch on that just yet. Here’s an example of an error thrown by Python for wrong data types.

 sum(121,'notanumber')
 TypeError Traceback (most recent call last) /tmp/ipykernel_7487/1877429733.py in ----> 1 sum(121,'notanumber') /tmp/ipykernel_7487/1004417429.py in sum(num1, num2) 1 def sum(num1, num2): ----> 2 return num1 + num2 3 4 def substract(num1, num2): 5 return num1 - num2 TypeError: unsupported operand type(s) for +: 'int' and 'str'

Functions in python are a very powerful way to define repetitive tasks that need to be applied in different parts of our code to compute with different values.