Sub topic 2
Identity, Truthiness, and Conditional Expressions
Assume you know basic Python syntax, variables, and built-in types such as int, str, list, dict, and bool.
Identity versus equality: `is` and `==`
Equality asks whether two objects have the same value. Identity asks whether two names refer to the same object.
- Use
==to compare values. - Use
isto compare identity. - Use
is Nonewhen testing forNone.
a = [1, 2]
b = [1, 2]
c = a
print(a == b) # True: equal contents
print(a is b) # False: different list objects
print(c is a) # True: the same object
value = None
print(value is None) # TrueDo not use is as a replacement for ==. Small immutable values can sometimes share objects as an implementation detail, which can make incorrect code appear to work.
Truthiness of values
Truthiness is the rule Python uses to interpret a value in a Boolean context, such as an if condition. False-like values include False, None, numeric zero, and empty strings, lists, tuples, sets, and dictionaries. Most other values are true-like.
Logical operators
and, or, and not combine or invert truth values.
not valueproducesTrueorFalse.left and rightneeds both operands to be true-like.left or rightneeds at least one operand to be true-like.
name = ""
display_name = name or "anonymous"
print(display_name) # anonymousShort-circuit evaluation and returned operands
and and or stop as soon as the result is known. They also return an operand, not necessarily a Boolean:
andreturns the first false-like operand, or the last operand.orreturns the first true-like operand, or the last operand.
print(0 and 1 / 0) # 0; the division is never evaluatedConditional expressions
A conditional expression chooses between two values in one line:
score = 72
result = "pass" if score >= 50 else "fail"
print(result)Read it as: “use pass if the condition is true; otherwise use fail.”
Exercise
What does [] or "empty" return, and why?
Show answer
It returns "empty" because an empty list is false-like, so or evaluates and returns its right operand.