Helper Functions
A helper function performs part of the computation of another function. It allows you to reuse common code without repeating ourselves. For instance, suppose you had a few lines of code that printed out the elapsed time at various points in a function:
import time def do_things(): start_time = time.perf_counter() for i in range(10): y = i ** 100 print(time.perf_counter() - start_time, "seconds elapsed") x = 10**2 print(time.perf_counter() - start_time, "seconds elapsed") return x do_things()
You should get the following output:
The print
statement is repeated twice in the preceding code, and will be better expressed as a helper function, as follows...