python-for-j277 / subroutines · Lesson 13
Lesson 13 — Subroutines
Subroutines: Functions
Subroutines that send a value back.
A function is a subroutine that works out an answer and returns it. You can store or use that answer however you like.
Returning a value
def double(number):
return number * 2
result = double(6)
print(result)
print(double(10))Output
12 20
How it works
returnsends a value back to wherever the function was called.double(6)works out 12 and hands it back; we store it inresult.- You can also use the returned value straight away, like printing
double(10).
A function that builds an answer
def area(width, height):
return width * height
print("Area:", area(4, 5))
total = area(2, 3) + area(4, 5)
print("Total:", total)Output
Area: 20 Total: 26
How it works
- This function returns the area instead of printing it.
- Because it returns a value, you can use it inside other calculations.
area(2, 3) + area(4, 5)adds the two returned answers together.
Procedure or function?
| Procedure | Function | |
|---|---|---|
| Does | Carries out a task | Works out and returns a value |
| Sends back | Nothing | A value, using return |
| Used like | show_area(4, 5) | total = area(4, 5) |
return ends itOnce
return runs, the function stops immediately — any lines after it are skipped.The deciding questionIf a subroutine gives you an answer back with
return, it is a function. If it just does a job, it is a procedure.What you have learned
- A function returns a value with
return. - The returned value can be stored or used inside an expression.
returnends the function straight away.- Functions return a value; procedures do not.