Python Booleans
In Python, Booleans are a fundamental data type used to represent logical values.
A Boolean can hold only two possible values:
• True
• False
Booleans play a crucial role in decision-making, comparisons, and control flow.
Boolean Expressions
Any expression in Python that involves comparison or logic evaluates to either True or False.
Example: Comparing Values
Python evaluates each expression and returns a Boolean result.
Booleans in Conditional Statements
Booleans are commonly used in if-else statements to control program execution.
Example: Conditional Logic
Here, Python checks the condition and executes code based on whether it is True or False.
Evaluating Values with bool()
The bool() function allows you to test any value and determine its Boolean truth value.
Example: Evaluating Direct Values
Truthy Values in Python
Most values in Python evaluate to True when converted to Boolean.
Examples of truthy values:
• Non-empty strings
• Non-zero numbers
• Non-empty collections (lists, tuples, sets, dictionaries)
Example
Falsy Values in Python
Only a limited set of values evaluate to False.
Examples of falsy values:
• False
• None
• 0
• Empty strings
• Empty collections
Example
Custom Objects and Boolean Evaluation
An object can also evaluate to False if its class defines a __len__() method that returns 0.
Example
Even though the object exists, Python treats it as False.
Functions Returning Boolean Values
Functions can return Boolean results and be used directly in conditions.
Example: Boolean Function
Example: Using Function in Condition
Built-in Functions That Return Booleans
Python provides many built-in functions that return Boolean values.
One commonly used function is isinstance().