🚨

# What are Logical Operators?

and and or or not

Before, we've seen mathematical operators like

`+`

, `-`

and `%`

. We know about relational operators like `==`

, `>=`

, `<=`

, `>`

, `<`

and so on, that compare two values to each other. Now, we learn how to string together many of these conditions to create **compound condition statements.**First, we'll discuss how the three basic logical operators work:

`not`

, `or`

and `and.`

The

`not`

operator does not change the way control flows, which is why we discuss it first. It changes a Truth-y value to a False-y one, and vice-versa.>>> not True

False

>>> not False

True

>>> not "61a"

False

>>> not []

True

>>> not (200 == 300)

True

The

`or`

operator **returns the first Truth-y value it finds, or — in case no Truth-y value is found — the last False-y value it finds**.>>> 1 or 2

1

>>> 0 or 1

1

>>> 0 or None

None

>>> 0 or None or 1

1

The

`and`

operator **returns the first False-y value it finds, or — in case no False-y value is found — the last Truth-y value it finds**.>>> 1 and 2

2

>>> 0 and 1

0

>>> None and 0

None

>>> 0 and None and 1

0

Notice how

`and`

and `or`

behave complimentarily from each other!So what is so special about

`and`

and `or`

? Here's the special thing — when they find their first False-y and first Truth-y value respectively, they return that value and do not keep reading that sentence!Let's take an example:

>>> 0 or 1 or 1/0

1

We know that 1/0 typically throws a

`Division by Zero Error`

. However, this statement does not do so! Instead, it finds the first Truth-y value — `1`

— and returns it, not even reading the `1/0`

at the end of the expression.Let's also take a similar example for

`and`

:>>> 1 and 0 and 1/0

0

Last modified 1yr ago