The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

96 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


The first of these lines is an instruction from Thonny telling the Python interpreter to run
the program you just saved. The second is the output of the program – the message you told
Python to print. Congratulations: you’ve now written and run your first Python program in both
interactive and script modes!

Next steps: loops and code indentation
Just as Scratch uses stacks of jigsaw-like blocks to control which bits of the program are
connected to which other bits, Python has its own way of controlling the sequence in which
its programs run: indentation. Create a new program by clicking on the New icon in the
Thonny toolbar. You won’t lose your existing program; instead, Thonny will create a new tab
above the script area. Start by typing in the following:

print("Loop starting!")
for i in range ( 10 ):

The first line prints a simple message to the shell, just like your Hello World program. The
second begins a definite loop, which works in the same way as in Scratch: a counter, i, is
assigned to the loop and given a series of numbers – the range instruction, which is told
to start at the number 0 and work upwards towards, but never reaching, the number 10 – to
count. The colon symbol (:) tells Python that the next instruction should be part of the loop.
In Scratch, the instructions to be included in the loop are literally included inside the
C-shaped block. Python uses a different approach: indenting code. The next line starts with
four blank spaces, which Thonny should have added when you pressed ENTER after line 2:

print("Loop number", i)

The blank spaces push this line inwards compared to the other lines. This indentation is
how Python tells the difference between instructions outside the loop and instructions inside
the loop; the indented code is known as being nested.
You’ll notice that when you pressed ENTER at the end of the third line, Thonny automatically
indented the next line, assuming it would be part of the loop. To remove this, just press the
BACKSPACE key once before typing the fourth line:

CHALLENGE: NEW MESSAGE
Can you change the message the Python program prints
as its output? If you wanted to add more messages, would
you use interactive mode or script mode? What happens if
you remove the brackets or the quotation marks from the
program and then try to run it again?0.
Free download pdf