Yesterday your programs ran straight through, top to bottom. Today they start
making choices — and every choice comes down to one question: is this True or
False?
Comparison operators
print(3 < 5)
print(3 > 5)
print(3 <= 3)
print(3 == 3) # equal to - two equals signs
print(3 != 3) # not equal to
age = 20
print(age >= 18)
print(type(age >= 18))= and == are different
= assigns a value; == asks a question. age = 18 sets the age. age == 18
checks it. Mixing them up is a rite of passage — Python catches it as a
SyntaxError in an if, which is more than most languages do for you.
Comparisons work on strings too, alphabetically by character code:
print("apple" < "banana")
print("Zoe" < "adam") # uppercase sorts before lowercase
print("apple" == "Apple")
print("apple".lower() == "Apple".lower())
# Python lets you chain comparisons, and it reads exactly as it looks.
score = 75
print(60 <= score < 90)That last line is genuinely nice: 60 <= score < 90 is one expression, and
score is evaluated once. Few languages allow it.
Combining conditions
and, or and not join conditions together. Python spells them as words,
not symbols.
age = 25
has_ticket = True
print(age >= 18 and has_ticket)
print(age >= 65 or has_ticket)
print(not has_ticket)
# and requires both; or requires at least one.
print(True and False)
print(True or False)
# Parentheses make mixed expressions readable.
is_free = (age < 12) or (age >= 65)
print(f"Free entry: {is_free}")With Boolean operands, and gives True only when both are true, and or
gives True when at least one is true. More generally, and and or return
one of their operands; they do not convert the result to a Boolean. not
always produces True or False. The examples below show why that matters.
Truthiness
Every Python value can be treated as a condition, not just True and False.
For the built-in values used here, zero, empty containers and strings,
None, and False are false in a condition. Nonzero numbers and nonempty
containers and strings are true. A nonempty string such as "False" is still
true; Python does not interpret its spelling as a Boolean.
# These are all "falsy":
print(bool(0), bool(0.0), bool(""), bool([]), bool({}), bool(None))
# Everything else is "truthy":
print(bool(1), bool(-3), bool("hello"), bool(" "), bool([0]))This is why you will see if name: rather than if name != "": in real
Python. It reads as "if there is a name", which is what you meant.
None is not False
None is Python's "no value at all" — what a function returns when it returns
nothing. It is falsy, but it is not False, and it is not 0. Test for it
with is None, never with == None.
Short-circuiting
and and or stop as soon as the answer is settled. This is not a
micro-optimisation — it is a tool for writing safe conditions.
# The right side is skipped when the left side settles the result.
text = ""
print(len(text) > 0 and text[0] == "A")
text = "Ada"
print(len(text) > 0 and text[0] == "A")
# or returns an operand: use a fallback only when the name is empty.
name = ""
print(name or "Guest")
print("Ada" or "Guest")Before you write your own
Predict. Four lines — the last one has a trap in it.
budget = 50
spent = 42
print(spent < budget)
print(spent == 42 and budget > 100)
print(not spent)
print(bool(""), bool("0"))Check your prediction
True
False
False
False Truenot spent is False because 42 is truthy. And "0" is a string with one
character in it — not empty, so truthy — even though the number 0 is falsy.
Fix. This should print True on a Saturday or Sunday and False otherwise.
It's Monday. Run it: what comes out isn't even True or False.
day = "mon"
is_weekend = day == "sat" or "sun"
print(is_weekend)Check your fix
day = "mon"
is_weekend = day == "sat" or day == "sun"
print(is_weekend)FalsePython read the original as (day == "sat") or "sun". The left side is False,
so or moved on and gave back its right side — the string "sun", which is
truthy. Each side of an or has to be a whole condition on its own.
Password checker
Write a condition that decides whether a password is acceptable. It must be at
least 8 characters long and have no surrounding whitespace. These are the
two rules for this exercise. Print True or False — for "hunter2000" that's
True. Then try "hunter2" and " hunter2000 ", which should both print
False, for different reasons. Use only the string operations and comparisons
you have already learned.
password = "hunter2000"
# Your code hereHint 1: the idea
Two separate yes/no questions, joined by and: is it long enough? Does it
already match its stripped version? Each question is one comparison.
Hint 2: a first step
Start by comparing the length with 8 and store that Boolean result. Then compare the original text with its stripped version, and only then combine the two results.
Show one solution
password = "hunter2000"
long_enough = len(password) >= 8
no_surrounding_space = password == password.strip()
print(long_enough and no_surrounding_space)Naming the two halves before combining them is worth the extra lines: the final condition then reads as a sentence rather than a puzzle.
What you learned
==!=<><=>=produceTrueorFalse;=assigns.- Comparisons chain:
0 <= x < 10. and,or,notcombine conditions, and they short-circuit.- Zero, empty built-in collections and strings,
None, andFalseare falsy. Nonemeans "no value"; test it withis None.