DEV Community


Charming the Python: Boolean & Operators

vickilanger profile image Vicki (she/her) Updated on ・2 min read

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.

Boolean & Operators

  • Boolean
  • Operators
    • Arithmetic
    • Comparison
    • Logical


True or False are the only possibilities with a boolean. However, you can use them for yes/no questions and many other things too.

is_dog = False
is_coding = True
is_programmer = True
is_cat = False
is_human = true  # this is true, but will error because it isn't capitalized
Enter fullscreen mode Exit fullscreen mode

True and False are constants with the values 1 & 0

True == 1
False == 0
Enter fullscreen mode Exit fullscreen mode


Operators are the constructs which can manipulate the value of operands. -reference

+ - * / % // **  # math or arithmetic operators
== != < > <> >= <=  # comparison operators
and or not  # logical operators
Enter fullscreen mode Exit fullscreen mode

Arithmetic Operators

I gave a bunch of examples in the post below.

Comparison Operators

you can compare numbers, words, lists, and more

Operator What it is Example
== equals 2 == 2
!= does not equal 2 != 7
> greater than 9 > 2
>= greater than or equal to 9 >= 9 or 9 >= 7
< less than 4 < 6
<= less than or equal to 4 <= 7

Logical Operators

and or not are useful for making decisions

dog_needs_exercise = True
is_awake = True

if dog_needs_exercise and is_awake:
    print("Take dog for a walk")
Enter fullscreen mode Exit fullscreen mode
dog_hungry = False
is_dinner_time = True

if dog_hungry or is_dinner_time:
    print("Feed dog")
Enter fullscreen mode Exit fullscreen mode
# getting paid this week?

a = "go to work"
b = "get work done"

if a and b:
    print("You get paid")  # because you did both

if a or b:
    print("You won't get paid")  # because you didn't do both
Enter fullscreen mode Exit fullscreen mode

Series based on

Discussion (9)

hanpari profile image
Pavel Morava • Edited

OK, I don't want to downplay your post or something, but you should know a few things.

Firstly, True and False are constants with value 1 and 0 respectively. and and or do not evaluate to True or False in Python, at least not in the way you think.

See this lines of code:

assert True == 1
assert False == 0
assert True + False == 1
assert 10 * True == 10

assert "one" or "two" == "one"
assert (("one" or "two") == True) == False
assert "one" and "two" == "two"
assert "one" and [] == []
assert "" or [] == []

assert False == bool("") == bool([]) == bool({})
assert True == bool("something") == bool(["something"]) == bool({"something"})

I suggest to play a little in interactive Python for better understanding. Hope it helps.

vickilanger profile image
Vicki (she/her) Author

Thanks for letting me know.

I've added a note about the values.

I know and & or don't directly evaluate to True & False. I was trying to simplify the example, but I think I oversimplified it. I'll come up with something that doesn't come across that way. I wanted to make sure if a beginner comes across the post that it's not using anything too advanced.

hanpari profile image
Pavel Morava

In this case, you simplified things to that extent, they became factually incorrect. 😁

I wrote my comment because I still remember my struggle to understand the code using and and or this way.

Thread Thread
vickilanger profile image
Vicki (she/her) Author

I definitely don’t want it to be incorrect. The only example I keep thinking of is a while loop, but that’s a bit more advanced than the current notes.

Thread Thread
hanpari profile image
Pavel Morava • Edited

People use or abuse this construction. It is shorter but harder to understand. Not to speak it may backfire eventually.

return x or y

instead of

return x if x else y

One can never understand such code if one thinks and or or evaluate to True/False.

Thread Thread
vickilanger profile image
Vicki (she/her) Author

As mentioned before, True/False is actually 1/0. So, are you saying we should be using and & or to evaluate to 1/0?

I’ve tried to find examples that don’t lead to a Boolean outcome and I’m at a loss.

I read the python docs this morning and it refers to these as Boolean operators.

Thread Thread
hanpari profile image
Pavel Morava • Edited

Interesting question. In Python bool built-in evaluate objects to True/False constants according to dunder __bool__ method of object.

See, for instance, this simple example:

class Positive:
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        return self.value > 0

plus_ten = Positive(10)
minus_ten = Positive(-10)
minus_twenty = Positive(-20)

assert bool(plus_ten) == 1 == True
assert bool(minus_ten) == 0 == False

assert (minus_ten or plus_ten).value == 10

# This is actually the tricky part
# and the reason why it is not great idea to evaluate
# your expression like this
# instead ternary X if Expr else Y

assert bool(plus_ten and minus_ten) == False
assert (plus_ten and minus_ten).value == -10
assert bool(minus_ten or minus_twenty) == False
assert (minus_ten or minus_twenty).value == -20

Note my last lines. The result of expressions is not true, yet Python returns the last of them, which is evidently False. It is OK in conditional statement, but certainly not OK, if you use return X or Y.

Python uses short-circuit evaluation, meaning, the and or or expressions return the last thing they had to evaluate. In X or Y if X is True, Y is never evaluated. Similarly, in X and Y there is no need to evaluate Y if X is already False.

Thread Thread
vickilanger profile image
Vicki (she/her) Author • Edited

So, part of my problem understanding your original post was that I had never seen assert before. I've read up on it and now I think I can make sense of this.

If I'm now understanding correctly, and & or statements seem similar to if, else, and elif statements.

I'm thinking something like this is a simple enough example.

dog_hungry = False
is_dinner_time = True

if dog_hungry or is_dinner_time:
    print("Feed dog")
Thread Thread
hanpari profile image
Pavel Morava

You are quite diligent.

I am using assert as simple testing tool.

If my assertion was wrong, I would end up with Assert Exception, not posting anything.

Typically, I am using this style to prevent myself from posting incorrect information.

It never came to my mind, someone would have trouble to decipher it. My bad.

and and or are operators, similar to plus or minus.

For instance,
1+3 = 4.


1 and 3 = 3
1 or 3 = 1

I mean they are not evaluating to True or False as you may think. The result is the last evaluated operand.

In if statement, the evaluated expression is checked whether it is True or False.

Meaning that
if (1 and 3):

is processed in following manner:

1 and 3 = 3

Because Python has to evaluate both operands in this case and result is the last evaluated one, 3.

bool(3) = True

Thus if condition is met.

The conversion to boolean is made internally by Python.

The other languages, for instance Java or C#, require you to write your condition more explicitly.

And if I am not mistaken, C# has two logic operators

For instance, & evaluates both operands, while && behaves similar to Python's and.

It is important to have good understanding of this, or you may run into hard to find bugs, which are not obvious when you don't know what you are looking at.

By the way, since I wrote this from my mobile, I had no opportunity to check my assertions. Be cautious 😊

Forem Open with the Forem app