Python functions
grouping code into actionable chunks
2025-11-04 15:56
// updated 2025-11-04 18:15
// updated 2025-11-04 18:15
Functions organize a bunch of statements into chunks that we can edit easily and re-use in different places:
def add_stuff(input1, input2, input3):
sum_inputs = input1 + input2 + input3
return sum_inputsUnpacking the above:
def= keyword that declares the functionadd_stuff= the name of the function- one word beginning with a letter but can contain digits and underscores
(input1, input2, input3)= the parameters of the function:= starts the function blockreturn= gives back a value to whichever piece of code used the function
We can then use (call) this function like such:
x = add_stuff(3, 2, 5)
print(x)
y = add_stuff(1, 2, 2) + add_stuff(-1, 2, 3)
print(y)
z = add_stuff("a", "b", "c")
print(z)
# Output
# 10
# 9 (i.e. 5 + 4)
# abc (i.e. strings glued together)Note that the arguments refer to the specific values that we insert when calling the function, while the parameters refer to the generic template of those values!
Recursive functions
A recursive function calls itself from within, a classical example being the calculation of a factorial (e.g. 4 factorial = 4! = 4 x 3 x 2 x 1):
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num-1)It has the general idea of a looping structure in that it:
- removes repetition
- i.e. the
elsestatement recursively calling the function
- i.e. the
- contains a "control statement" to break out of it
- i.e. the
ifstatement above
- i.e. the
Recursion in programming and web development primarily happens with nested structures such as objects and arrays (lists)!