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 * radiusIf 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 * radius2What 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 resultlet'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
returna 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.55goes in as the inputr- The body of the function runs,which store
78.5in theresultvariable within the function body - THe function return the
resultvariable, which means thearea_of_circle(5)expression evaluates to78.5 78.5is stored in theareavariable and then printed
Source: boot.dev