The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 5 Programming with Python 99

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Click the Stop icon on the Thonny toolbar to tell the program to stop what it’s doing –
known as interrupting the program. You’ll see a message appear in the Python shell area, and
the program will stop – and without ever reaching line 4.


Conditionals and variables
Variables, as in all programming languages, exist for more than just controlling loops. Start a
new program by clicking the New icon on the Thonny menu, then type the following into the
script area:


userName = input ("What is your name? ")

Click the Run icon, save your program as Name Test, and watch what happens in the shell
area: you’ll be asked for your name. Type your name into the shell area, followed by ENTER.
Because that’s the only instruction in your program, nothing else will happen – except that the
variables area, to the right of the Thonny window (Figure 5-5), will automatically display the
variable and its value. The variables area remains even when the program isn’t running, making
it easy to see what your program has been doing.


5 Figure 5-5: The variables area helps you to track variables and their values


CHALLENGE: LOOP THE LOOP
Can you change the loop back into a definite loop again?
Can you add a second definite loop to the program? How
would you add a loop within a loop, and how would you
expect that to work?
Free download pdf