On using conditional if-else statements in Python
We live in a contingent world. That’s why it’s so hard to make predictions with any accuracy. Are you going to live in your current house for the next ten years? Well, that depends. If we don’t inadvertently produce more kids and if we can afford to add on a new adults-only bathroom and if my boss doesn’t continue to drive me bonkers and if interest rates continue to climb like kudzu and if… Well, you get the idea. It’s all about how various conditions shape up.
Programmers need to worry about lots of contingencies as well. That’s why, in the world of programming, we have “conditional statements.” That’s usually just a fancy name for lines of code that begin with the world “if.” The programmer has to work out the possible conditions in advance.
Let’s say you want to write a program that automatically gives people their horoscopes. Well, that horoscope will be contingent on what year the person was born, what time they were born, what hour they were born, whether Venus was in retrograde (whatever that even means), etc. In short, there are a whole lot of “ifs” here.
Let’s start at a basic level. Write the following short code in a text editor and run it. (Don’t forget the indents because Python is extremely sensitive to those, which is a subject for another post!)
height = 8
if height == 8: print ("Hiya, Charlie! Nice stilts!") else: print ("Hey, Charlie, no stilts today?")
You should get the message, “Hiya, Charlie! Nice stilts!” Now, go ahead and assign the variable “height” to a smaller value such as 5 or 6 and run the code again. Because the condition of height changed, you got a different response. Such is the power of “if” and it’s sidekick “else”. If you can master “if,” you can prepare your code for a world in which conditions change and the future always looks iffy.
PS – If you want more information on conditionals, I recommend the Hands-on Python Tutorial.
Featured image from Tall Camp. Author Jennifer Morrow from San Francisco. Wikimedia Commons.