Screencast on while vs. if in Makecode
Screencast on translation
In Makecode, the blue if statement cannot run on it self, so I put it into a “on start” block so that the code would run. Similarly, the while loop also needs to be inside the “on start” block. As you can see, the two programs are completely identical other than the while loop between the two blocks in the second program. Similarly, to change the while program into an if program, I simply took out the “While True” line and deleted the spaces before the if and else conditions.
After trying out these two sets of programs on the CPx, I came to the understanding that without the while loop enclosing the if statement, the program would only run through the if statement once. On the other hand, if we add in the while loop surrounding it, the program would run for as long as the condition of the while loop remains true. My screencast (linked above) shows the differences using animation on the CPx simulator provided by the Adafruit website.
In the translation of Makecode to Python (or Python to Makecode, for that matter), it is important to pay attention to the slight stylistic differences, although most functional lines are similar between the platforms. In the above example, for example, it is quite easy to identify the “set all pixels to___” blocks, the while loops, and the if statement conditions in both platforms.
In Makecode, all commands must be put into a general block, usually the “forever” block that I used on the outermost. This block makes sure that the contents inside this block runs again and again. It is most commonly used in conjunction with the while loop. There is also the “on start” block, which only runs through all the code enclosed in it once.
In Mu, it was imperative that I imported certain functions from datasets so that functions would run. I also had to set the initial sensor setting to 0, and attribute a variable name to the light sensor.
Essentially, this program told the CPx to shine white light if light level <= 100, shine red light if 100 < light level < 200, and shine green light if light level >= 200. Because all these commands are in a while loop, which means that it runs through the commands multiple times, as I change the light level, the CPx would change colors accordingly.