If you’ve spent enough time perusing the App Inventor “blocks” menu, then you’ve probably noticed the components that say “for each” in the “Control” menu. These are known as “for loops”, and they’re essential tools not only in App Inventor but in programming in general.
App Inventor has 3 “for loops”:
- for each item in a list: This loop lets you cycle through each entry in a list, completing the blocks inside the loop for each one.
- for each number from (1, 5, 1): This loop is very similar to the first, except that it cycles through numbers rather than text items on a list.
- for each key with value in dictionary: This loop is slightly different from the others as it cycles through key-value pairs in a dictionary.
What are “for loops” exactly?
A “for loop” is a control flow statement that allows you to repeat a block of code a certain number of times. In MIT’s App Inventor, a for loop can be useful in many different situations, particularly when you want to repeat an action multiple times or when you want to perform an action on a list of items.
One instance when you might use a for loop in App Inventor is if you have a list of items that you need to iterate through and perform an action on each one. For example, you could use a for loop to cycle through a list of colors and set the background color of your app to each one in turn.
Below is an example of a simple for loop that takes a list of numbers and adds 5 to each digit. The loop is designed to run just once when you press the button – that’s what the “if” statement is for.
As you can see, “for loops” can be a very powerful tool. Get used to them, as you’re going to be using them often. Put simply, you won’t be able to do much in App Inventor without them.