DEV Community


Discussion on: Charming the Python: Boolean & Operators

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 😊