Raspberry while-loop
Let's first take a look at a program written with while-loop statement:
a=0
print("loop start")
while a < 5 :
print(a)
a = a + 1
print("loop end")
The program is first executed in the sequence structure. At the beginning of the program, we first declare a variable “a" and print a line of characters “loop start" with print().
a=0
print("loop start")
·Note·
What is a variable?
Variables are values that have no fixed values and can be changed at any time. We use variables to store data so that they can be called in later portions of our code. In a program, a variable generally has two aspects: variable name and variable value. The variable name is the identity of the variable, whereas the variable value is the value stored in the variable. For example, in the above code, “a” is the variable name whereas 0 is the variable value. When multiple variables are used in a programme, unique names are used to distinguish them.
Variables in Python do not need to be declared. Each variable must be assigned before use, and will be created at the same time as when it is first assigned.
Next, we use the while statement to create a definite loop structure. This specifies that when the variable “a" is less than 5, the program should repeatedly execute the instructions contained in the while statement. That is, it should print out the value of “a", and add one to “a", until “a" is greater than or equal to 5.
while a < 5 :
print(a)
a = a + 1
The output of the program is as follows:
loop start
0
1
2
3
4
loop end
Looking at the execution results of the sample program, we can find that the program does not start to execute the last print() statement until it has executed several loops within the while statement.
But, how does the computer know which statements need to be repeated in the while loop statement and which statements are outside the while loop statement? MicroPython uses indentation and colon “:" to distinguish the levels between code blocks, unlike other programming languages (such as Java and C) which use braces “{}" to separate code blocks. This change makes code written in MicroPython clear and easy to understand.
·Note·
Python is very strict on code indentation. The same level of code block indentation must be consistent. In general, we can use BACKSPACE or TAB to complete the indentation. However, whether we manually type multiple spaces or use TAB to indent, we usually define the length on an indentation as four spaces (by default, one tab is equal to four spaces).