A condition in Python: making code depend on a test

A condition is the test Python evaluates to true or false in order to decide whether a block of code runs, or is skipped.
5 min read
Believemy logo

Definition

A program that always runs the same instructions in the same order can only handle one situation: the same shipping fee for every basket, whoever the customer is. For it to adapt, it needs a point where it looks at what it has in front of it before deciding what comes next.

A condition is that point: an expression Python evaluates to true or false, and on which the execution of a block of code depends. If it is true, the block runs. If it is false, Python steps over it and picks up further down, as though those lines were not there.

The word names the test itself, not the syntax that hosts it. That is why it turns up in several places in the language: behind an if, behind an elif, behind a while, where it decides whether the loop goes round again, and even inside comprehensions.

Here is the most common shape: a test, a colon, then an indented block that only runs if the test passes.

PYTHON
if basket.total > 50 and client.is_active:
    # This block only runs if both halves of the test are true
    apply_free_shipping()


The comparison operators

What remains is writing the test itself. The question asked is almost always a comparison between two values: does this total clear the threshold, is this answer the one expected?

Six forms cover almost everything. The table below gives, for each one, the exact moment Python judges it true.

WrittenTrue when
==Both values are equal
!=They differ
< and >One is strictly smaller or larger
<= and >=Same, including equality
inThe value belongs to a collection
isBoth names point at the same object

The last two rows stand apart. in does not compare two values, it asks whether a value sits inside a collection. is does not either: it asks whether two names point at the same object in memory. Hence a classic mistake: writing is to compare values works on small integers, by accident, then turns wrong further on.

Python also allows a form few languages do: chaining. if 0 <= score <= 20: reads like mathematics and evaluates score only once.


Every object has a truth value

A condition does not have to be a comparison. You can put any value in it, a list, a string, a number or an object, and Python takes care of reducing it to true or false.

It applies the same rule to everything: whatever is empty, zero or None is false, everything else is true. A list with no items is therefore false, and so is a string with no characters.

You no longer need to count in order to know whether there is anything. Instead of measuring with len and then comparing the result to zero, you write if results:, which reads as "if there are results".

Warning

That shortcut turns into a trap the moment zero is a legitimate value. if quantity: silently rules out a quantity of zero, which is not the same as no quantity at all, and the flaw shows up neither on a reread nor in the usual test data. When zero means something, write the comparison out in full: if quantity > 0:.


Combining without slipping

A real decision rarely rests on a single test: free shipping applies above a certain amount and to active customers only.

Three operators join conditions together: and, which requires both halves to be true, or, which is happy with one, and not, which flips a test.

Python evaluates them lazily: it reads from left to right and stops as soon as the answer is settled. Inside an and, a false first half already makes the whole thing false, so the second never runs.

PYTHON
# If client is None, Python stops here: the second half is never evaluated
if client is not None and client.is_active:
    ...

This is not an optimisation detail, it is a guard: the first half of the test makes sure the second one only runs on an object that exists. Swapping the two halves would raise an AttributeError the moment client is None.

The order of the tests therefore carries meaning: what protects comes first. And when a condition grows long, and binds before or: explicit brackets beat a bet on precedence.


Frequently asked questions

Question

Why is my condition always true?

The most common case is a non-empty value used as a test without anyone noticing, as in if answer == "yes" or "YES":. Python reads two separate conditions here, and the string "YES" on its own is non-empty, therefore always true. The correct writing goes through in: if answer in ("yes", "YES"):.

Question

Should == True be written in a condition?

No, it is redundant: if active: already says what if active == True: spells out at greater length, since Python reduces the value to true or false anyway. The explicit comparison only earns its place when the variable may hold something other than a boolean.

Question

How can several possible values be tested?

With in and a collection, which stays readable even with ten values, rather than with a long chain of or where the variable eventually gets left out of one of the halves. Picking the right writing for a condition is one of the first habits our Python course works on.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.