python – Role of helper functions?

python – Role of helper functions?

A helper function is a function that performs part of the computation of another function

— from Google

def add(a, b): # <-- This is a helper function
    return a + b

def main():
    subtract = 10 - 9
    multiply = 2 * 2
    add(5, 4) # <-- Helper function is called here

The add(5, 4) is a helper function. You have already defined add(a, b) and added the required functionality in the function. Now you can use that add function as many time as you like, wherever you like and it will add two integers for you.

So the add function is helping you to add two integers as many times as you like, wherever and whenever you like.

A helper function is a function you write because you need that particular functionality in multiple places, and because it makes the code more readable.
A good example is an average function. Youd write a function named avg or similar, that takes in a list of numbers, and returns the average value from that list.
You can then use that function in your main function, or in other, more complex helper functions, wherever you need it. Basically any block of code that you use multiple times would be a good candidate to be made into a helper function.
Another reason for helper functions is to make the code easier to read. For instance, I might be able to write a really clever line of code to take the average of a list of numbers, and it only takes a single line, but its complicated and hard to read. I could make a helper function and replace my complicated line with one thats much easier to read.

python – Role of helper functions?

It means that you can create additional functions that might help you complete the project.

Oftentimes, an assignment or test will provide you with a specific function signature. That might imply that youre only allowed to code within that one function to solve the problem.

By specifying that youre allowed to use helper functions, its saying that youre not limited to just the one function. You can create others to be called from within the specified function.

To be more specific for your case: your assignment requires you to complete the following functions:

  • admissionStatus(sat_math,sat_reading,sat_writing,class_rank)
  • isValid(sat_math,sat_reading,sat_writing,class_rank)
  • a main function

Then, the assignment says:

Implement some of the computations within admission status as separate functions that can be called from admission status.

What computations are available there? Computing the average test score, say. Pythons standard library doesnt contain a pre-written function for computing an average. So, you write your own function to do that.

From Calculating arithmetic mean (average) in Python:

def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

That would be an example of a helper function.

Leave a Reply

Your email address will not be published. Required fields are marked *