Learn Python the Hard Way: A Deceptively Simple Introduction to the Terrifyingly Beautiful World of Computers and Data Science, 5th Edition
by Zed A. Shaw
Exercise 31
Else and If
In the previous exercise, you worked out some if-statements and then tried to guess what they are and how they work. Before you learn more, I’ll explain what everything is by answering the questions you had from Study Drills. You did the Study Drills, right?
What do you think the
ifdoes to the code under it? Anif-statementcreates what is called a “branch” in the code. It’s kind of like those choose-your-own-adventure books where you are asked to turn to one page if you make one choice and another if you go a different direction. Theif-statementtells your script, “If this Boolean expression is True, then run the code under it; otherwise skip it.”Why does the code under the
ifneed to be indented four spaces? A colon ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access