The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

100 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


To make your program do something useful with the name, add a conditional statement by
typing the following:

if userName == "Clark Kent":
print("You are Superman!")
else:
print("You are not Superman!")

Remember that when Thonny sees that your code needs to be indented, it will do so
automatically – but it doesn’t know when your code needs to stop being indented, so you’ll
have to delete the spaces yourself.
Click the Run icon and enter your name into the shell area. Unless your name happens to be
Clark Kent, you’ll see the message ‘You are not Superman!’. Click Run again, and this time type
in the name ‘Clark Kent’ – making sure to write it exactly as in the program, with a capital C
and K. This time, the program recognises that you are, in fact, Superman (Figure 5-6).

5 Figure 5-6: Shouldn't you be out saving the world?

The == symbols tell Python to do a direct comparison, looking to see if the variable
userName matches the text – known as a string – in your program. If you’re working with
numbers, there are other comparisons you can make: > to see if a number is greater than
another number, < to see if it’s less than, => to see if it’s equal to or greater than, =< to see if
it’s equal to or less than. There’s also !=, which means not equal to – it’s the exact opposite of
==. These symbols are technically known as comparison operators.
Free download pdf