...

/

Part 1: Creating Functions for an Automatic Light Application

Part 1: Creating Functions for an Automatic Light Application

Learn how to create functions in the automatic light application.

Functions for the automatic light application

We learned how to create functions that can take arguments and return values. Let’s put all of this together and use it in a more realistic application, our automatic light app.

If we again go back to our application for turning on the lights outside our house and focus on the application running on our phone, we’ll see that we have at least two distinct things that we need to do over and over again.

We’ll need to get our current position and calculate our distance to home so we know if it’s time to turn on the lights.

These are two distinct tasks, and they’re very well suited to being packaged up into two different functions, namely, get_current_position and calculate_distance_to_home, as shown in the following figure:

Press + to interact
Main application calls two different functions
Main application calls two different functions

The illustration above shows that we have a block that we call main_application. This is a function, and it calls a function called get_current_position that will return the longitude and latitude, indicating the current position of the phone. Equipped with this information, main_application can now make another function call, this time, to a function called calculate_distance_to_home, and pass the longitude and latitude that were just obtained to it. This function will do some calculations and return either true or false, indicating whether we are within the range or not.

The question is, how do we decide that we need to divide the code into these ...