What Is a Condition in Python?

A photo depicting a fork in the road with the title of the article overlayed.

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

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:

Likewise, here are some external resources for folks learning Python (#ad):

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.

The Python Concept Map (8 Articles)—Series Navigation

An activity I regularly do with my students is a concept map. Typically, we do it at the start and end of each semester to get an idea of how well our understanding of the material as matured over time. Naturally, I had the idea to extend this concept into its own series, just to see how deeply I can explore my own knowledge of Python. It should be a lot of fun, and I hope you enjoy it!

Jeremy Grifski

Jeremy grew up in a small town where he enjoyed playing soccer and video games, practicing taekwondo, and trading Pokémon cards. Once out of the nest, he pursued a Bachelors in Computer Engineering with a minor in Game Design. After college, he spent about two years writing software for a major engineering company. Then, he earned a master's in Computer Science and Engineering. Today, he pursues a PhD in Engineering Education in order to ultimately land a teaching gig. In his spare time, Jeremy enjoys spending time with his wife and kid, playing Overwatch 2, Lethal Company, and Baldur's Gate 3, reading manga, watching Penguins hockey, and traveling the world.

Recent Code Posts