Functions
A collection of statement collected and executed within what is called a function to be used sometime in the program. Functions always follow this format:
def function_name(parameter1):
statement
return
From above def means to define a function or begin the process of creating one.
When selecting a function name, you follow the same rules as when selecting a variable name.
Parameters are basically variables that you’re able to use within the scope of the function and are assigned whatever value or expression when you first called it.
The statement is any piece of code that you want to run.
Return passes back to you whatever is typed after and exits the function.
So to be frank, that won’t make a lot of sense to anyone who hasn’t written python so I’ll write some examples.
The formula for determining perimeter, area and volume of a rectangular shapes.
perimeter = 2 * (length + width)
area = (length * width)²
volume = length * width * height
First, write the first line.
Line 01: def perimeter()
Now, we want the parameters which end up becoming are variables within the function.
Line 01: def perimeter(length, width):
Next, second line will use the variables length and width.
Line 01: def perimeter(length, width):
Line 02: perimeter = length * width
As you can see we are assigning the result of length * width to a new variable called perimeter which is going to be returned to you once return is executed.
Line 01: def perimeter(length, width):
Line 02: perimeter = length * width
Line 03: return perimeter
This is how it’ll look.
def perimeter(length, width):
perimeter = length * width
return perimeterprint(perimeter(2, 4)) <- Use the print function to show what was returned.
To write the functions for area and volume, just follow the same format.
def area(length, width):
area = (length * width) ** 2
return area
print(area(4, 4))def volume(length, width, height):
volume = length * width * height
return volume
print(volume(3, 6, 9))