The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

98 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Indentation is a powerful part of Python, and one of the most common reasons for a
program to not work as you expected. When looking for problems in a program, a process
known as debugging, always double-check the indentation – especially when you begin
nesting loops within loops.
Python also supports infinite loops, which run without end. To change your program from
a definite loop to an infinite loop, edit line 2 to read:

while True:

If you click the Run icon now, you’ll get an error: name 'i' is not defined. This is
because you’ve deleted the line which created and assigned a value to the variable i. To fix
this, simply edit line 3 so it no longer uses the variable:

print("Loop running!")

Click the Run icon, and – if you’re quick – you’ll see the ‘Loop starting!’ message followed by
a never-ending string of ‘Loop running’ messages (Figure 5-4). The ‘Loop finished!’ message
will never print, because the loop has no end: every time Python has finished printing the ‘Loop
running!’ message, it goes back to the beginning of the loop and prints it again.

5 Figure 5-4: An infinite loop keeps going until you stop the program

COUNT FROM ZERO
Python is a zero-indexed language – meaning it starts counting from
0, not from 1 – which is why your program prints the numbers 0
through 9 rather than 1 through 10. If you wanted to, you could change
this behaviour by switching the range (10) instruction to range (1, 11) –
or any other numbers you like.
Free download pdf