#π Booleans
11 messages Β· Page 1 of 1 (latest)
@errant schooner
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
bool is a type, much like, say, int. In fact, it's a subclass of int - that's why you can do True + True and get 2. Unlike most types, there's only two values a bool can take - either True or False. Whether something becomes True when converted to bool is called "truthiness". For the builtin types there are fairly consistent rules on what objects are truthy:
- a number is truthy if it's not equal to zero, falsy otherwise
- a collection (list, tuple, set, dict, and also including strings) is truthy if it's nonempty.
a Boolean (bool type in python) is a data type which represents a single logical value, True or False
when you use bool(something), that evaluates whenever that 'something' is considered true-ish or false-ish
traditionally you have 0 = false and 1 = true, but when converting from other types to booleans in python you have
0is False, all other numbers are treated as True- empty collections (text strings, lists, dictionaries, etc) are considered as False, and collections with at least one element are considered as True (effectively
bool(x) == bool(len(x))in this case) - other nonstandard objects can define a custom rule that determines whenever it returns true or false when evaluated
Another notable point: conditions, like in an if-statement, get implicitly cast to bool. You might have seen people do if some_lst: if you've read python code. That's equivalent to if len(some_lst) > 0:, since collections such as lists are truthy if they are nonempty.
also, as for why 0 = false, 1 = true: that is pretty much how things work ever since digital computers were invented
1 = on = true
0 = off = false
stares meaningfully at Bash yeah, imagine if it was 0 that's truthy, haha
Thanks!
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.
π Booleans