3: Conditionals/if and Code Blocks
November 30, 2016 Leave a comment
Book ref: 70ff
Python 2.7: Same, see earlier post
Note: this tutorial will be easier if you use Python-IDLE, not Python (Command Line).
So far, the programs you’ve written have gone straight from top to bottom, without skipping any lines. There are times though, when you do want a line to run only some of the time. For example, if you wrote a game, you’d only want one of these two lines of code to run:
print("Congratulations, you win!!!") print("Sorry, you lose.")
In fact, you’d want your code to look something like:
if player wins: print("Congratulations, you win!!") otherwise: print("Sorry, you lose.")
Python isn’t quite that much like English, but it’s pretty close. In Python you can do this by using the if and else (not otherwise) keywords, like this:
player_wins = True if player_wins: print("Congratulations, you win!!") else: print("Sorry, you lose.")
You see I’ve changed the two English words player wins to a single Python name player_wins. When you run this code, you get this output:
Congratulations, you win!!
If you change the line
player_wins = True
player_wins = False
(try it) then this is printed:
Sorry, you lose.
You need to remember that player_wins is just the name you’re using to store a value, the program can’t tell whether the player has won or lost. You need to set the value beforehand. You also need to notice that player_wins takes only two values – True and False (True and False are special values in Python, but you can take them as having their English meanings).
The if keyword needs to be followed by something that is either True or False. It could be a variable that holds one of those values or it could be an expression (see below) that evaluates to them. After “that something” you put a colon. The colon tells Python that a new code block is about to start. On the next line the code in the code block is indented. This indenting is important. Python will complain if the code is not indented (try it). If you want more things to happen, then you can put in more lines of code, as long as they’re all indented at the same level – that is, they have the same number of spaces in front of them (try 4 spaces in front). When you do more Python you’ll discover that you can put code blocks within code blocks – but that’s for later.
After the code block comes another keyword, else, followed by a colon and another code block. The else keyword serves the function of word otherwise in my mock code above. It is run if the if isn’t. After the else is another code block. This is indented like the first one and, like the first one, can contain more lines of code, as long as they are all indented with the same number of spaces in front of them.
Visually indented code blocks are one of Python’s great programming features. Most languages have code blocks, but few of them require them to be shown visually with indents. This makes Python programs easier to read and follow.
If you don’t have alternative code that is to be run if the conditional is not True, then you can leave out the else: and its code block. So, if you want to say Happy Birthday if it’s someone’s birthday, but nothing if it’s not, you could do something like this:
players_birthday = False if players_birthday: print("Happy Birthday!")
When you run this code, it doesn’t print anything, because you’ve set players_birthday = False and have not included an else block. Set players_birthday = True and see what happens.
Rather than setting a value of True or False expressly, you can include a comparison. Python has a lot of comparisons but the main ones are == (equal- note the two equal signs together, not one), > (greater than) and < (less than). Here are some of them in action:
>>> 1 == 1 True >>> 1 == 2 False >>> 1 > 2 False >>> 1 < 2 True
See how they give either a True or False result? Try some yourself. Make sure you know the difference between 1 = 2 and 1 == 2.
Going back to our earlier example, rather than having a name player_wins, you’re probably more likely to have something like players_score. You can then compare the score against a winning score and print your message. For example, if they players_score is 100 and a score of greater than 90 is a win you could code this:
players_score = 100 if players_score > 90: print("Congratulations, you win!!") else: print("Sorry, you lose.")
Run it, then change players_score = 90 and run it again.