Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain string boolean test result

Tags:

python

I have this code:

>>> char = 'A'
>>> 'A' == char
True
>>> ('A' or 'B') == char
True

Why does this not equal True?

>>> ('B' or 'A') == char
False
like image 744
minerals Avatar asked Aug 27 '26 02:08

minerals


1 Answers

Your expressions are not doing what you expect.

'A' or 'B'

This actually evaluates to 'A', try it out in the interpreter!

When you say

('A' or 'B') == char

The interpreter is actually doing these steps:

('A' or 'B') == char
('A') == char
True

But when you do

('B' or 'A') == char

The interpreter does this:

('B' or 'A') == char
('B') == char
False

What you probably wanted was:

'A' == char or 'B' == char
True
like image 120
Collin Avatar answered Aug 28 '26 16:08

Collin