The idea
Every decision a program makes comes down to a yes/no question. Is this order over Rp 300,000? Is the product in stock? Is the customer in Jakarta and a business account? Python answers these questions with booleans: a type with exactly two values, True and False.
You'll use booleans to filter data, to decide which code runs (the next module but one), and to write checks that catch bad data before it reaches a report.
Comparison operators
A comparison looks at two values and produces a boolean:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
< | less than | 3 < 5 | True |
> | greater than | 3 > 5 | False |
<= | less than or equal | 5 <= 5 | True |
>= | greater than or equal | 4 >= 5 | False |
total = 285000
print(total > 300000)
print(total >= 285000)
free_shipping = total >= 300000
print(free_shipping)
print(type(free_shipping))
False
True
False
<class 'bool'>
A comparison is just a value, so you can store it in a variable with a good name like free_shipping. Code that says if free_shipping: reads almost like English.
= assigns and == compares. total = 300000 changes total; total == 300000 asks whether it equals 300000. Mixing them up is one of the most common beginner bugs.
Comparing text
== works on strings too, and it's exact: case, spaces and punctuation all count.
city = "Jakarta"
print(city == "Jakarta")
print(city == "jakarta")
print(city.lower() == "jakarta")
print("Jakarta " == "Jakarta")
True
False
True
False
This is why the previous module made such a fuss about .strip() and .lower(): clean the text, then compare.
Strings can also be compared with < and >, which compares them alphabetically (technically, by character codes, so all capitals come before lowercase letters). "apple" < "banana" is True. Use this for sorting, not for checking amounts.
Chained comparisons
Python lets you write ranges the way you would in maths:
rating = 4.3
print(4.0 <= rating <= 5.0)
age = 17
print(18 <= age < 65)
True
False
4.0 <= rating <= 5.0 means "rating is between 4 and 5, inclusive". It's cleaner than writing two comparisons joined together.
Combining conditions: and, or, not
Real questions usually have more than one part. Python has three logical operators:
a and bisTrueonly if both are true.a or bisTrueif at least one is true.not aflipsTruetoFalseand back.
city = "Jakarta"
segment = "Business"
total = 450000
print(city == "Jakarta" and segment == "Business")
print(city == "Bandung" or total > 400000)
print(not total > 400000)
True
True
False
Reading the three results: the first is True because the city really is Jakarta and the segment really is Business. The second is True even though the city isn't Bandung, because or only needs one side, and the total is over 400000. The third flips total > 400000, which is True, into False.
Here's the full truth table for and and or, which covers every combination:
| a | b | a and b | a or b |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
When you mix and and or, and is evaluated first, just like * before +. Use brackets to make the grouping explicit:
is_vip = False
in_stock = True
total = 350000
eligible = (is_vip or total >= 300000) and in_stock
print(eligible)
True
Short-circuiting
Python stops evaluating as soon as it knows the answer. In a and b, if a is False the whole thing is False, so b is never even looked at. In a or b, if a is True, b is skipped. This lets you guard against errors:
quantity = 0
total = 0
print(quantity > 0 and total / quantity > 50000)
False
Without short-circuiting, total / quantity would crash with a ZeroDivisionError. Because quantity > 0 is already False, Python never tries the division.
Truthiness: what counts as True?
Python can treat any value as true or false, not just booleans. This is called truthiness. The "falsy" values are few and worth memorising:
FalseandNone- zero:
0,0.0 - empty things:
""(empty string),[](empty list),{}(empty dictionary)
Everything else is "truthy". bool() shows you how Python sees a value:
print(bool(0), bool(42))
print(bool(""), bool("Ayu"))
print(bool(None))
False True
False True
False
You'll see truthiness used in conditions like if name: to mean "if name isn't empty". It's idiomatic Python, but be careful: if quantity: is False for a quantity of 0, which might be a perfectly valid value. When zero is meaningful, write the comparison out: if quantity is not None:.
is versus ==
== asks "do these have the same value?". is asks "are these the very same object?". You'll only need is for one thing as a beginner: checking for None.
discount = None
print(discount is None)
True
Always write x is None (not x == None). It's the Python convention and it's always correct.
Why this matters for clean code
Name your conditions. if total >= 300000 and city in ("Jakarta", "Bandung") and not is_cancelled: is hard to read in one go, but free_shipping = total >= 300000 followed by if free_shipping and ships_locally and not is_cancelled: explains the business rule. A well-named boolean is documentation that can't go out of date.
Recap
- Booleans are
TrueandFalse. Comparisons (==,!=,<,>,<=,>=) produce them. =assigns,==compares.- String comparison is exact: clean text with
.strip()and.lower()first. - Chain comparisons for ranges:
low <= x <= high. and,or,notcombine conditions.andbinds tighter thanor, so use brackets.- Falsy values:
False,None,0,0.0,"",[],{}. Everything else is truthy. - Check for missing values with
x is None.