The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 5 Programming with Python 101

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


5 Figure 5-7: It will keep asking for your name until you say it’s ‘Clark Kent’


Comparison operators can also be used in loops. Delete lines 2 through 5, then type the
following in their place:


while userName != "Clark Kent":
print("You are not Superman - try again!")
userName = input ("What is your name? ")
print("You are Superman!")

Click the Run icon again. This time, rather than quitting, the program will keep asking for
your name until it confirms that you are Superman (Figure 5-7)– sort of like a very simple
password. To get out of the loop, either type ‘Clark Kent’ or click the Stop icon on the Thonny
toolbar. Congratulations: you now know how to use conditionals and comparison operators!


USING = AND ==
The key to using variables is to learn the difference between = and
==. Remember: = means ‘make this variable equal to this value’, while
== means ‘check to see if the variable is equal to this value’. Mixing
them up is a sure way to end up with a program that doesn’t work!
Free download pdf