13-functions.py
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

double.py
def double(number):
    return number * 2

result = double(6)
print(result)
print(double(10))
Output
12
20
How it works
  • return sends a value back to wherever the function was called.
  • double(6) works out 12 and hands it back; we store it in result.
  • You can also use the returned value straight away, like printing double(10).

A function that builds an answer

area.py
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?

ProcedureFunction
DoesCarries out a taskWorks out and returns a value
Sends backNothingA value, using return
Used likeshow_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.
  • return ends the function straight away.
  • Functions return a value; procedures do not.