Why does `and` return a string instead of `True` or `False`?
Quick answer
In Python, and uses truthiness to choose an operand; it does not promise to return True or False. It returns the first operand if that operand is false in a Boolean context; otherwise, it evaluates and returns the second operand. Since an empty string is false and a nonempty string is true, string results are expected. Use bool(expression) or an explicit comparison when you need a Boolean result. [S1]
The question, the details, the next step.
A practical checklist
Identify the first operand and check whether it is false in a Boolean context.
If the first operand is false, expect
andto return that operand; otherwise expect it to return the second operand.Remember that an empty string is false and a nonempty string is true in a Boolean context.
Wrap the expression in
bool(...)or use explicit comparisons when you requireTrueorFalse.Confirm that truthiness matches the condition you intend to test.
A few more useful answers
Does `and` always evaluate its second operand?
No. Python evaluates the second operand only when the first operand is true in a Boolean context; otherwise, it returns the first operand. [S1]
Why does `"hi" and "there"` return `"there"`?
A nonempty string is true in a Boolean context, so Python evaluates and returns the second operand. [S1]
How do I make the result of an `and` expression show as `True` or `False`?
Use bool(expression) or write explicit comparisons for the conditions you mean to test. [S1]
Sources
References used for this guide.
- [S1] Python Language Reference: Boolean operations and operand selection docs.python.org · Checked
