Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Booleans and Conditionals

Learn how Python decides: comparisons, the and/or/not trio, truthiness, and if, elif, and else branches that read like sentences.

Levels: Beginner ~15 min read

Basic

A program becomes interesting the moment it can choose. Python's choosing machinery is unusually close to plain English: a condition is an expression that boils down to True or False, and the if statement runs its block only when the condition holds. Master the small vocabulary around those two words and every branch you write will read back like the sentence you were thinking.

Comparisons produce booleans

python compare.py
1
2
3
4
5
6
7
loaves = 7

loaves > 5        # True
loaves == 7       # True   two equals: comparison
loaves != 7       # False
loaves >= 10      # False
name == "Nadia"   # False  if name is something else

Every comparison is a question with a boolean answer.

Comparisons chain in Python the way they do in mathematics, a small luxury worth using: 0 <= loaves < 10 is true when the count sits inside the range, and no other mainstream syntax says it that cleanly.

and, or, not: combining conditions

Conditions combine with lowercase keywords, not punctuation. In a condition, and requires both operands to be truthy and or requires at least one; not reverses truth value. The operators short-circuit: and stops at the first falsy operand, while or stops at the first truthy operand. That is why if orders and orders[0] == "rye": safely checks that a list has an item before reading its first item.

and and or return operand values

The value of an and or or expression is not necessarily True or False. With and, Python returns the first falsy operand, or the last operand if every operand is truthy. With or, Python returns the first truthy operand, or the last operand if every earlier operand is falsy. The not operator is different: it always returns a Boolean. This makes short-circuit expressions useful for choosing fallbacks and guarding access without an extra branch.

Interactive Runnable example
Edit

Ready to run.

Quick check

Which expression preserves a non-empty list as the result instead of converting its truth value to a Boolean or choosing a fallback?

items = [3, 5]
result = 
print(result)

Truthiness: every value has an opinion

Python can use any value as a condition, and every value lands on one side or the other. The falsy club is small and worth memorizing: False, None, zero of every kind, and empty containers, "", [], {}. Everything else is truthy, including the strings "no" and "false", a trap that bites anyone who forgets that non-empty text is simply true.

python truthy.py
1
2
3
4
5
6
7
name = ""
if not name:
    print("No name given")   # runs: empty string is falsy

items = ["rye"]
if items:
    print(f"{len(items)} item(s)")  # runs: non-empty is truthy

Emptiness itself becomes the condition.

This is why the Python idiom for checking a collection is if items: rather than if len(items) > 0:. Both are correct; one trusts the language to say what it means.

if, elif, else: the branch in full dress

The complete statement walks a ladder. Python tests each condition top to bottom and runs the first block that holds, skipping the rest entirely, with elif supplying as many middle rungs as needed and else catching whatever survived. Indentation is not decoration here; it is the block, and four spaces per level is the convention the whole language keeps.

python ladder.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
loaves = 7

if loaves == 0:
    print("Sold out")
elif loaves < 5:
    print("Last few loaves")
elif loaves < 20:
    print("Baking along nicely")
else:
    print("A very good Saturday")

One rung runs, and only one.

Put the machinery to work

The example below is a tiny order gate combining everything from the lesson. Run it, then change the three facts at the top and predict each output before running again. Then try removing the elif chain's final else and set open to False, to see what silence looks like when no rung matches, a legitimate result, and sometimes a bug you just removed the evidence of.

Interactive Runnable example
Edit

Ready to run.

What to notice

  • Exactly one ladder rung ran per evaluation, the first whose condition held.

  • The orders and len(orders) >= 3 line never crashes on an empty list, because and stops at the first false fact.

  • The final if chained the range check 7 <= hour < 12 exactly as mathematics writes it.


Quick check

If you can say which values are falsy without peeking, explain why an empty list fails an and before its length is ever consulted, and trace a three-rung ladder on paper, your programs can now decide. Next, lists gives them something substantial to decide about. When you are ready, take the Booleans and Conditionals quiz.

Was this page helpful?

Mark this learning resource complete to track your learning progress.