Creating and using variables

Creating variables

Variables are used to store values for later use in a program. In the example below, we store some text, referred to as a string in programming terminology. Then, we use this variable in the second line of the program, which is quite short.

some_variable = 'test'
basic.show_string(some_variable)

Naming variables

Note that the name of the variable is completely arbitrary. You can use any name you want for your variable, with some limitations. However, giving your variable a name that means something to you as a programmer is usually a good idea. That will make it easier to understand your program later on. In that respect, the name some_variable is not a very descriptive name that will help you understand the program. Here is a better example (see code snippet below). This code does the following:

button_A_state = input.button_is_pressed(Button.A);
celsius = input.temperature();
fahrenheit = (celsius * 9) / 5 + 32;

Changing variables

Variables can be changed and overwritten as part of the program. The following code provides an example. Here, the temperature is stored as temperature. The next line uses this variable and overwrites the variable after converting the temperature to degrees Fahrenheit.

temperature = input.temperature()
temperature = (temperature * 9/5) + 32

Creating an infinite main loop

As discussed in class, your program will likely contain an infinite main loop. The image below shows how the main loop allows your program to react to the sensory input. In the case of the micro:bit, these include input from light sensors, the button, and the accelerometer.

Untitled

You can create an infinite loop using the while True statement. This is computer speak for do the following over and over again. The following code provides an example. It flips between showing two images on the LEDs array over and over again.

image1 = IconNames.ANGRY
image2 = IconNames.SURPRISED

while True:
    basic.pause(500)
    basic.show_icon(image1)
    basic.pause(500)
    basic.show_icon(image2)

In the example above, these lines are inside the while loop. That means they are executed again and again. Python understands that they are part of the while loop because they are indented.