Booleans
What Are Booleans?
- Booleans represent one of two values:
TrueorFalse.
Boolean Values:
- In programming, you often need to know if an expression is true or false.
- Python allows you to evaluate any expression and get
TrueorFalse.
Comparing Values:
When you compare two values, Python returns a Boolean answer.
pythonprint(10 > 9) print(10 == 9) print(10 < 9)- Output:
True - Output:
False - Output:
False
- Output:
Evaluate Values and Variables:
The
bool()function allows you to evaluate any value and returnTrueorFalse.pythonprint(bool("Hello")) print(bool(15))- Output:
True - Output:
True
- Output:
Evaluating variables:
pythonx = "Hello" y = 15 print(bool(x)) print(bool(y))- Output:
True - Output:
True
- Output:
Most Values Are True:
Almost any value is evaluated to
Trueif it has some sort of content.- Any string is
True, except empty strings. - Any number is
True, except 0. - Any list, tuple, set, and dictionary are
True, except empty ones.
pythonprint(bool("abc")) print(bool(123)) print(bool(["apple", "cherry", "banana"]))- Output:
True - Output:
True - Output:
True
- Any string is
Some Values Are False:
Empty values, such as
(),[],{},"", the number0, and the valueNoneevaluate toFalse. The valueFalsealso evaluates toFalse.pythonprint(bool(False)) print(bool(None)) print(bool(0)) print(bool("")) print(bool(())) print(bool([])) print(bool({}))- Output:
False - Output:
False - Output:
False - Output:
False - Output:
False - Output:
False - Output:
False
- Output:
- Booleans are fundamental in programming for evaluating expressions and controlling the flow of code with conditions. Practice using Boolean values, the
bool()function, and conditions to understand their importance in Python!