For Beginners

Lesson 18/23

A Loop for Each List

Imagine you have a list and you want each of its elements displayed in Notepad, for example. There are couple ways to accomplish this — think how you could solve such problem.

Here you have a simple, clean and efficient code, which will do the job:

♥list = Adam❚Eva❚John❚Mary
program notepad
foreach ♥name in ♥list
    keyboard Name=♥name⋘enter⋙

Run it and see the results.

The foreach loop is designed specifically for lists and in this example it defines a variable called ♥name, which will retrieve each element from the ♥list, one at a time. Then the keyboard command writes Name= in the Notepad and inserts the retrieved element, then goes to a new line and starts over with the next element in a list.

Note: If you wanted to use spaces in the text sent to Notepad, you'd have to embrace this text with the triple quote character:

    keyboard ‴Name = ♥name⋘enter⋙‴

The next lesson shows you how to test conditions.