While creating some of the other early articles in this series, I had a realization: something even more fundamental than loops and if statements is the condition. As a result, I figured we could cover the concept of a condition today.
Table of Contents
- Concept Overview
- What Does a Condition Look Like?
- Where Else Can Conditions Be Used?
- Are There Limits on Conditions?
- Making Decisions
Concept Overview
In programming, the concept of a condition is fundamental. Without them, we wouldn’t be able to make decisions in our programs. So then, what are they?
In the broadest terms, a condition is an expression that evaluates to true of false. These return values can then be used to inform a decision.
Typically, you will most often see conditions employed in common control flow structures like loops and if statements. In the case of a loop, the condition determines if we continue looping.
while condition: # do something
Meanwhile, in an if statement, the condition determines if we execute a block of code.
if condition: # do something
Therefore, as you might imagine, conditions are very powerful ways of controlling the execution of a program.
Naturally, you probably want to know more! As a result, we’ll use the rest of this article to answer some of your questions.
What Does a Condition Look Like?
Conditions can take many forms, but they’re only valid if they evaluate to a boolean (i.e., true or false). Therefore, to write a condition, you need to be familiar with a variety of operators.
Some operators interact with boolean values directly, so we often call them boolean operators. These operators include the and
, or
, and not
operators.
Whether you’re familiar with boolean logic or not, you can probably guess how to use the boolean operators. For both the and
and or
operators, we must compare two different expressions, like in the phrase “this and that” as well as in the phrase “this or that.” Meanwhile, the not
operator only works on a single value, such as in the phrases “not this” and “not that”.
Of course, boolean operators are not the only way to produce a boolean value. We can also take advantage of the relational operators. If you recall your elementary math classes, then you already know many of the relational operators, which are used to compare numbers. For example, if you want to know if one number is greater than another number, you can use the greater than operator (i.e., >
).
As you can probably imagine, the boolean operators and the relational operators can be used together to create some truly expressive conditions, such as the following:
True and False # False 5 > 3 # True 2 * 3 > 2 * 4 # False False or 3 == 3 # True
With that said, you might be looking at these conditions and thinking that they don’t do anything, and you’d be right. Generally, conditions are only useful if we incorporate variables. That’s how we end up with code that’s a bit more interesting:
grade = int(input("Enter a number between 0 and 100")) if grade >= 70: print("You pass!") else: print("You fail!")
Notice how in this example we can get different outcomes depending on what the user enters. That’s the power of a condition!
Where Else Can Conditions Be Used?
At its core, a condition is just a boolean expression. Therefore, anywhere you might use a boolean expression is a good place for a condition. While we typically think of conditions in control flow structures, you may see them as function inputs.
As a silly example, strings have a method called splitlines
, which gives you a list of lines from a given string. It has exactly one parameter called keepends
that keeps the line endings, which defaults to False
. Normally, if you wanted to keep the endings, you would just set it to True
. However, nothing is stopping you from setting it based on a condition (e.g., keep endings if the text is from a particular source).
Outside of parameters, conditions can also be used in places like ternary operators, list comprehensions, and generator expressions. These are slightly more advanced structures than if statements and loops, but you’ll recognize the conditions in them immediately, such as in the following list comprehension:
[num for num in [1, 4, 3] if num > 2] # returns [4, 3]
Are There Limits on Conditions?
You may be surprised to know that conditions can be as complex as you want as long as they evaluate to a true or false. Typically, however, we don’t want to be stuck reading through a messy boolean expression, so we often wrap complicated logic into functions. The result is a much more readable chunk of code:
if isRainy(town) and isCold(town): print("I'm not going to work today")
In the example above, we have two functions which do most of the heavy lifting for us. For instance, maybe both functions query a weather API to determine if it’s cold and raining. While it may be possible to embed all that code directly in the condition, it’s much more readable to abstract it away into functions.
Making Decisions
Previously, I’ve written about making choices in Python, which covers a lot of the topics in this article in more detail. So, head over there if you want to learn more.
In the meantime, let’s call this concept covered for the day! As always, if you liked this article, there is plenty more like it below:
- The Haters Guide to Python
- 5 Things You Should Know Before You Pick Up Python
- Dump Java: Life Is Just Better in Python
Likewise, here are some external resources for folks learning Python (#ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
And finally, you can take your support a step further by heading over to my list of ways to grow the site. Otherwise, take care! We’ll hopefully see you back here soon.
Recent Code Posts
Today, we're expanding our concept map with the concept of loops in Python! Unless you're a complete beginner, you probably know a thing or two about loops, but maybe I can teach you something new.
Today, we're talking about constructors! Specifically, we'll look at the __init__() special method in Python, which functions as a constructor.