When Does Your Code Get Iffy?

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. 

Published by

Mark R. Vickers

I am a writer, analyst, futurist and researcher. I've spent most of my working life as an editor and manager for research organizations focusing on social, business, technology, HR and management trends. But, perhaps more to the point for this blog, I'm curious about the universe and the myriad, often mysterious relationships therein.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s