Functions allows us to reuse and organize code. For example we have some code that calculates the area of a circle:

radius = 5
area = 3.14 * radius * radius

If we want to calculate the area of other circles we could copy and paste the code:

radius1 = 5
area1 = 3.14 * radius1 * radius1

radius2 = 7
area2 = 3.14 * radius2 * radius2

What if we need to calculate the area of 1000 of circles? Thats where functions help. We can define a new function called area_of_circle using the def keyword.

def area_of_circle(r):
	pi = 3.14
	result = pi * r * r
	return result

let's break the area_of_circle function down:

  • It takes one input (aka "parameter" or "argument") called r
  • After the :, the indented lines form the function body - this is the code block that will run each time we use (aka "call") the function.
  • It return a single value (the output of the function). In this case, it's the value stored in the result variable

To call this function (use this function) we can pass in any number as the argument for the parameter r, and capture the output in a new variable.

area = area_of_circle(5)
print(area)
#78.5
  1. 5 goes in as the input r
  2. The body of the function runs,which store 78.5 in the result variable within the function body
  3. THe function return the result variable, which means the area_of_circle(5) expression evaluates to 78.5
  4. 78.5 is stored in the area variable and then printed

Source: boot.dev