Why do we need functions?
Why do we need functions? Well, imagine if you are going to write some complicated Mathematical formula. Without functions, you will have to rewrite (and copy-and-paste) the formula over and over again
x = 5
y = 1.1
z = 8
a = 2 * x + y
a = a * y + z**x
a = 2**a + z * 3
a = x * z + y
x = 1
y = 0.2
z = 4
a = 2 * x + y
a = a * y + z**x
a = 2**a + z * 3
a = x * z + y
x = 7
y = 1
z = 0.3
a = 2 * x + y
a = a * y + z**x
a = 2**a + z * 3
a = x * z + y
With functions, we can abstract away your complicated formula, so that your code is more readable.
def award_winning_formula(x, y, z):
a = 2 * x + y
a = a * y + z**x
a = 2**a + z * 3
a = x * z + y
return a
n = award_winning_formula(5, 1.1, 8)
n = award_winning_formula(1, 0.2, 4)
n = award_winning_formula(7, 1, 0.3)
And one day you might develop bigger formulas or applications that will use this formula. Thus you can easily reuse your formula, abstract the details of the formula from the bigger formulas/applications, and keep your code easy to maintain.
def my_patent_pending_formula(p, q, x, y, z):
b = p + x * q
b = q**2 - 3 * award_winning_formula(x, y, z)
b = 1 / (b + min([award_winning_formula(x**2, 2 * y, 0), b, p + q]))
b = b + award_winning_formula(p, b, q)
return b
n = my_patent_pending_formula(p, q, x, y, z)
So the key motivation for functions is that you can abstract your algorithms, and reuse them for different inputs. It also makes your code more readable and easier to maintain.