Functions
A function is very similar to a procedure. Both are blocks of code that do a specific job. The main difference is:
- A procedure performs some steps
- A function performs some steps and then sends a value(s) back to where it was called
We do this using the return statement.
Example
def calculate_area(width, height):
area = width * height
return area
- The function is called calculate_area.
- It takes two parameters: width and height.
- It multiplies them to work out the area.
- The return line sends the result back.
How return works
When Python reaches the return statement:
- That value after return is sent back to where the function was called
- The function then ends immediately – no more lines in the function are run after return
This means you can store the result in a variable, or use it in another calculation.
Function design
- Parameters pass data into a subprogram.
- Return passes data out of a subprogram.
Comparing Rectangle Area
- Calculate area of rectangle 1
- Calculate area of rectangle 2
- Compare area of rectangles
| 1 | Calculate area of rectangle 1 | IN | width, height |
| OUT | area | ||
| 2 |
Calculate area of rectangle 2
|
IN | width, height |
| OUT | area | ||
| 3 |
Compare area of rectangles
|
IN | area1, area2 |
| OUT |
| 1.1 | area = width * height |
| 1.2 | return area |
| 2.1 | if area1 > area2 |
| 2.2 | display “Area 1 is bigger” |
| 2.3 | else |
| 2.4 | display “area 2 is bigger” |
def calc_area(width, height):
area = width * height
return area
def compare_areas(area1, area2):
if area1 > area2:
print("Area 1 is bigger")
else:
print("Area 2 is bigger")
# Main
area1 = calc_area(10,20)
area2 = calc_area(5,10)
compare_areas(area1, area2)