Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions python-boolean/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Python Booleans: Use Truth Values in Your Code

This folder provides the code examples for the Real Python tutorial [Python Booleans: Use Truth Values in Your Code](https://realpython.com/python-boolean/).

## Setup

All scripts except `numpy_arrays.py` use only the Python standard library, and you need Python 3.6 or later to run them.

The NumPy example needs NumPy. Create and activate a virtual environment, then install the pinned dependency:

```sh
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

## Usage

Each script covers one part of the tutorial:

- `boolean_type.py`: The Python Boolean type, Booleans as keywords and as numbers
- `boolean_operators.py`: The `not`, `and`, and `or` operators and short-circuit evaluation
- `comparison_operators.py`: Equality, order comparisons, `is`, `in`, and chained comparisons
- `boolean_testing.py`: Truthiness of `None`, numbers, sequences, and custom objects, plus `all()` and `any()`
- `numpy_arrays.py`: How NumPy arrays behave in a Boolean context

Run any of them with Python:

```sh
$ python boolean_type.py
```
40 changes: 40 additions & 0 deletions python-boolean/boolean_operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# The not Boolean operator
print(not True)
print(not False)


def print_and_true():
print("I got called")
return True


print(not print_and_true())


# The and Boolean operator
def print_and_return(x):
print(f"I am returning {x}")
return x


print(True and print_and_return(True))
print(True and print_and_return(False))
print(False and print_and_return(True))
print(False and print_and_return(False))


def inverse_and_true(n):
1 // n
return True


print(inverse_and_true(5))
try:
inverse_and_true(0)
except ZeroDivisionError as error:
print(f"ZeroDivisionError: {error}")
print(False and inverse_and_true(0))

# The or Boolean operator
print(True or print_and_true())
print(False or print_and_true())
171 changes: 171 additions & 0 deletions python-boolean/boolean_testing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import datetime
import decimal
import fractions
import math

# Boolean testing in if statements
if 1 == 1:
print("yep")
if 1 == 2:
print("yep")

# None as a Boolean value
print(bool(None))


def add_num_and_len(num, things=None):
return num + len(things or [])


print(add_num_and_len(5, [1, 2, 3]))
print(add_num_and_len(6))

# Numbers as Boolean values
print((bool(3), bool(-5), bool(0)))
print([bool(x) for x in [0, 1.2, 0.5, math.inf, math.nan]])
print(bool(0.1 + 0.2 + (-0.2) + (-0.1)))
print(0.1 + 0.2 + (-0.2) + (-0.1))
print((bool(fractions.Fraction("1/2")), bool(fractions.Fraction("0/1"))))
with decimal.localcontext(decimal.Context(prec=3)) as ctx:
print(bool(ctx.create_decimal(math.pi) - ctx.create_decimal(22) / 7))
with decimal.localcontext(decimal.Context(prec=4)) as ctx:
print(bool(ctx.create_decimal(math.pi) - ctx.create_decimal(22) / 7))

# Sequences as Boolean values
print((bool([1]), bool([])))
print((bool((1, 2)), bool(())))
print((bool({1, 2, 3}), bool(set())))
print((bool({1: 2}), bool({})))
print((bool("hello"), bool("")))
print((bool(b"xyz"), bool(b"")))


# Other types as Boolean values
def func():
pass


print(bool(func))


def before_noon():
return datetime.datetime.now().hour < 12


def greet():
# Bug: the missing parentheses make before_noon always truthy
if before_noon:
print("Good morning!")
else:
print("Good evening!")


greet()


class Dummy:
pass


print(bool(Dummy()))


class BoolLike:
am_i_truthy = False

def __bool__(self):
return self.am_i_truthy


x = BoolLike()
print(bool(x))
x.am_i_truthy = True
print(bool(x))


class ExcludedMiddle:
def __bool__(self):
raise ValueError("neither")


x = ExcludedMiddle()
try:
bool(x)
except ValueError as error:
print(f"ValueError: {error}")


class DummyContainer:
my_length = 0

def __len__(self):
return self.my_length


x = DummyContainer()
print(bool(x))
x.my_length = 5
print(bool(x))


class AlwaysTrue:
def __bool__(self):
return True


class AlwaysFalse:
def __bool__(self):
return False


print((bool(AlwaysTrue()), bool(AlwaysFalse())))
try:
len(AlwaysTrue())
except TypeError as error:
print(f"TypeError: {error}")


class BooleanContainer:
def __len__(self):
return 100

def __bool__(self):
return False


x = BooleanContainer()
print(len(x))
print(bool(x))

# Operators and functions
print(not 1)
print(not 0)
print(1 and 2)
print(0 and 1)
print(1 or 2)
print(0 or 2)


def summarize(long_text):
if len(long_text) <= 4:
return long_text
return long_text[:2] + "..." + long_text[-2:]


print(repr(summarize("hello world")))
print(repr(summarize("hi")))
print(repr(summarize("")))
try:
summarize(None)
except TypeError as error:
print(f"TypeError: {error}")

for a in ["hello world", "hi", "", None]:
print("-->", summarize(a or ""))

print(all([1, 2, 3]))
print(all([0, 1, 2]))
print(all(x / (x - 1) for x in [0, 1]))
print(any([1, 0, 0]))
print(any([False, 0, 0.0]))
print(any(1 / x for x in [1, 0]))
26 changes: 26 additions & 0 deletions python-boolean/boolean_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# The Python Boolean type
print(type(False))
print(type(True))

# Python Booleans as keywords
a_true_alias = True
print(a_true_alias)

# Python Booleans as numbers
print(True == 1)
print(False == 0)
print(True + (False / True))

lines = """\
He took his vorpal sword in hand;
Long time the manxome foe he sought—
So rested he by the Tumtum tree
And stood awhile in thought.
""".splitlines()
print(sum("the" in line.lower() for line in lines) / len(lines))

# Breaking the calculation into its parts
print(["the" in line for line in lines])
print(False + True + True + False)
print(len(lines))
print(2 / 4)
84 changes: 84 additions & 0 deletions python-boolean/comparison_operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Equality and inequality
print(1 == 1)
print(1 == 1.0)
print(1 == 2)
print(1 != 2)
print(1 != (1 + 0.0))

# Order comparisons
try:
{1: 3} < {2: 4}
except TypeError as error:
print(f"TypeError: {error}")

try:
1 <= "1"
except TypeError as error:
print(f"TypeError: {error}")

print(1 <= 1)
print(1 < 1)
print(2 > 3)
print(2 >= 2)

# The is operator
x = []
y = []
print(x is x)
print(x is not x)
print(x is y)
print(x is not y)

# The in operator
small_even = [2, 4]
print(1 in small_even)
print(2 in small_even)
print(10 in small_even)
print("e" in "hello beautiful world")
print("x" in "hello beautiful world")
print("beautiful" in "hello beautiful world")
print("belle" in "hello beautiful world")

# Chaining comparison operators
print(1 < 2 < 3)
print(1 < 2 and 2 < 3)
print(1 < 3 < 2)
print(1 < 3 and 3 < 2)
print(1 < 2 < 1)
print(1 == 1.0 < 0.5)
print(1 == 1.0 == True)
print(1 < 3 > 2)
print(1 < 2 < 3 < 4 < 5)

# Short-circuit chain evaluation
try:
2 < "2"
except TypeError as error:
print(f"TypeError: {error}")
print(3 < 2 < "2")
print(3 < 2 < (1 // 0))


def foo():
print("I'm foo")
return 1


print(0 < foo() < 2)
print((0 < foo()) and (foo() < 2))

hours_worked = 5
print(1 <= hours_worked <= 25)

# Mixing operators and chaining
a = 0
print(a is a < 1)
print((a is a) < 1)
print(a is (a < 1))
print(a < 1)
print("b" in "aba" in "cabad" < "cabae")

greeting = "hello"
quality = "good"
end_greeting = "farewell"
print(greeting is not quality not in end_greeting)
18 changes: 18 additions & 0 deletions python-boolean/numpy_arrays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import textwrap

from numpy import array

x = array([0])
print(len(x))
print(bool(x))

y = array([0, 1])
try:
bool(y)
except ValueError as exc:
print("\n".join(textwrap.wrap(str(exc))))

try:
bool(array([]))
except ValueError as exc:
print(f"ValueError: {exc}")
1 change: 1 addition & 0 deletions python-boolean/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
numpy==2.5.5
Loading