This is the first post for our Technovation Team, and will be a series of tutorials and resources from which we've cobbled together our little App.
The first lesson I wanted to go over, was a problem I noticed from working with the girls on MIT App Inventor 2. Something they really needed to be better familiar with. Loops. For Loops, While Loops, and Do... While Loops.
One of the strengths of programming you learn early on, is being able to tell the computer to do a lot of repetitive tasks easily. This is what loops are for.
Say you have a database full of information. It might look like this:
How would you add up all the volunteer hours together? The best way is to use a for each loop.
First you would need to create a list to get all the Tags from the database.
The list called Database_Tags should now look like this;
Here is where you should start the for loop, to get the program to start looking through each line of information, and adding the hours together. You will also need a global variable named Sum_Hours to save the total amount of hours after this procedure is complete.
Now let's look at what this does specifically:
It means that for each item in Database_Tags, which in this case, contains 7 items, it does everything nested in the for loop block, as outlined by the green box.
Here is a sample through the first few iterations
The logic follows this pattern; the code in the "do" part of the loop is executed to the end for the first item, then it goes back to the beginning and executes again for the 2nd item, and so on, until the last item in the list.
Hence the name, loop.
But alas, things are not so easy in App Inventor land. If we read the fine print for the TinyDB object, we see that there can only be one repository per app:
Everything we want to save goes into the same data repository. So, instead of the database looking like what we originally surmised, it might instead look like this:
There's a lot of junk information in there that we don't want when we sum the total number of Volunteering Hours. Luckily for us, we had the foresight to save all the relevant volunteer information with the "Volunteering:" prefix.
In order to filter out the data that we want, we can add an if/then statement to the for loop:
If the tag information from each for loop contains the piece of text "Volunteering", it then sends the code to the part where it adds the hours. If the piece is missing, it skips the "then" part of the code and goes on to the next item in the list.
And there we go, that's how loops work, and I hope everyone has a clearer picture now of what's actually going on when we call a for loop. It makes things easier when there's a lot of information, and we want the machine to do all of the legwork.
Next tutorial we will jump to how to use MIT App Inventor to connect to Google Drive API.
References: My Brain.
Good.
ReplyDelete