Thứ Sáu, Tháng Hai 7, 2025
spot_img
HomeStudybool() function in Python

bool() function in Python

 

What is Bool in Python? How is the Bool function in Python used? Let’s find out with Quantrimang.com!

In the Python programming language, the bool() function is used to convert a value to a Boolean (True or False) using a standard truth-checking procedure. So how to use the bool() function? We invite you to find out in this article.

Syntax of bool() function

bool([gia_tri])

Parameters of bool() function:

Usually, function parameters bool() will be a value. It is not required to pass a value to the bool() function, and in case there is no value, the function bool() will return False.

What value does the bool() function return?

Jaw bool() returns True or False:

  • False: If the value is False or not transmitted.
  • True: If the value is True.

The following values ​​will be evaluated by Python as False:

  • None
  • False
  • The number 0 of any numeric data type, such as 0, 0.0, 0j.
  • Empty sequences like (), [ ]’ ‘.
  • map is empty like { }.
  • Object or class has __bool__() or __len()__ returns 0 or False.

All values ​​outside the above list are True.

Example of bool() function

ktra = []
print(ktra,'là',bool(ktra))

ktra = [0]
print(ktra,'là',bool(ktra))

ktra = 0.0
print(ktra,'là',bool(ktra))

ktra = None
print(ktra,'là',bool(ktra))

ktra = True
print(ktra,'là',bool(ktra))

ktra="Quantrimang.com"
print(ktra,'là',bool(ktra))

In this program, we will check a series of values, see if the bool() function returns False or True, we have the following output:

[] là False
[0] là True
0.0 là False
None là False
True là True
Quantrimang.com là True

Python bool as keyword

Integration names are not keywords. As for the Python language, they are regular webs. If you bind them, you will override the built-in value.

In contrast, the names True and False are not built-in. They are keywords. Unlike many other Python keywords, True and False are Python expressions. Because they are expressions, you can use them anywhere an expression can be placed, such as 1+1.

You can assign a Boolean value as a variable, but you cannot assign a value to True:

>>> a_true_alias = True
>>> a_true_alias
True
>>> True = 5
  File "", line 1
SyntaxError: cannot assign to True

Since True is a keyword, you cannot attach a value to it. Apply the same rule for False:

>>> False = 5
  File "", line 1
SyntaxError: cannot assign to False

You cannot assign False because it is a keyword in Python. This way, True and False behave like other constants. For example, you can pass 1.5 to functions or attach it to variables. However, you cannot assign a value to 1.5. The statement 1.5 = 5 is not valid Python. Both 1.5 = 5 and False = 5 are invalid Python code and will cause a SyntaxError when parsed.

Xem thêm  COUNTIF function: Conditional counting in Excel

The bool() function in Python is a built-in function used to evaluate a value or expression and return its Boolean value, either True or False. Boolean values are fundamental in Python, as they are the backbone of decision-making structures like if and while statements. Below is a comprehensive guide to the bool() function, its behavior, and its applications.


1. Definition and Syntax

The bool() function is defined as follows:

python
bool([value])
  • Parameters:
    The function accepts a single optional argument (value). If no argument is provided, it returns False.
  • Return Value:
    The function returns:

    • False if the value is considered falsey.
    • True if the value is considered truthy.

2. Truthy and Falsey Values in Python

Python evaluates objects and values as either truthy or falsey when used in a Boolean context. This behavior applies to the bool() function as well.

2.1 Falsey Values

These are values that evaluate to False in a Boolean context:

  • None: Represents the absence of a value.
  • False: The Boolean False itself.
  • Numeric values: 0, 0.0, 0j (integer, float, and complex numbers).
  • Empty sequences/collections: '' (empty string), [] (empty list), () (empty tuple), {} (empty dictionary), set() (empty set), and frozenset().
  • Empty ranges: range(0).

2.2 Truthy Values

Any value not listed above is considered truthy, including:

  • Non-zero numbers: 1, -1, 3.14, etc.
  • Non-empty sequences: 'abc', [1, 2, 3], (0,), etc.
  • Objects: Instances of classes (unless they define their own __bool__() or __len__() method that returns False).

3. Behavior and Examples

Let’s explore how bool() behaves with different data types and values.

Xem thêm  Programming a face detection tool in Python

3.1 With Numbers

  • Integers:
    python
    print(bool(0)) # False
    print(bool(42)) # True
    print(bool(-1)) # True
  • Floating-point numbers:
    python
    print(bool(0.0)) # False
    print(bool(3.14)) # True
  • Complex numbers:
    python
    print(bool(0j)) # False
    print(bool(1+1j)) # True

3.2 With Strings

  • An empty string is False, while any non-empty string is True:
    python
    print(bool('')) # False
    print(bool('Python')) # True

3.3 With Sequences

  • Empty sequences are False, and non-empty sequences are True:
    python
    print(bool([])) # False
    print(bool([1, 2])) # True
    print(bool(())) # False
    print(bool((3, 4))) # True
    print(bool(range(0))) # False
    print(bool(range(1))) # True

3.4 With Dictionaries and Sets

  • Empty collections are False, and non-empty collections are True:
    python
    print(bool({})) # False
    print(bool({'a': 1})) # True
    print(bool(set())) # False
    print(bool({1, 2, 3})) # True

3.5 With None

  • None always evaluates to False:
    python
    print(bool(None)) # False

3.6 With Custom Objects

  • By default, custom objects are True, unless they define a __bool__() or __len__() method that explicitly returns False:
    python
    class MyClass:
    pass

    class MyFalseClass:
    def __bool__(self):
    return False

    print(bool(MyClass())) # True
    print(bool(MyFalseClass())) # False


4. Applications of bool()

4.1 Type Conversion

The bool() function is commonly used to convert values to their Boolean equivalents:

python
print(bool(1)) # True
print(bool(0)) # False
print(bool('Hello')) # True
print(bool('')) # False

4.2 Conditional Expressions

Although direct evaluation is more common in conditional statements, bool() can explicitly clarify the intent:

python
x = [1, 2, 3]
if bool(x):
print("x is non-empty")

4.3 Input Validation

The function can be used to check whether a user input is valid or not:

python
user_input = input("Enter something: ")
if bool(user_input):
print("You entered:", user_input)
else:
print("You entered nothing!")

4.4 Default Values in Functions

bool() can evaluate whether to use default or provided arguments:

python
def func(param=None):
if bool(param):
print("Using provided parameter:", param)
else:
print("Using default parameter")

func() # Using default parameter
func("Hello") # Using provided parameter: Hello


5. Performance Considerations

The bool() function is highly optimized for checking the truth value of objects. However, in contexts where a direct truth test (if value) suffices, using bool() is redundant and slightly less performant. For example:

python
x = [1, 2, 3]
if x: # Preferred
print("x is non-empty")

if bool(x): # Redundant
print("x is non-empty")


6. Customizing Boolean Behavior

As mentioned, objects can override the default truthiness by implementing special methods:

  • __bool__(): Should return True or False.
  • __len__(): If __bool__() is not defined, Python checks the length using __len__(). A length of 0 means False.

Example:

python
class MyCustomClass:
def __len__(self):
return 0

print(bool(MyCustomClass())) # False


7. Key Points to Remember

  1. The bool() function is a convenient way to evaluate truthiness.
  2. Empty values (like 0, None, []) are False, while all others are True.
  3. You can customize truthiness for objects using __bool__() or __len__().

8. Common Mistakes

  1. Redundant Use: Using bool() unnecessarily in conditions.
    python
    if bool(x): # Redundant
  2. Confusion with is: Remember that bool(x) evaluates the truthiness of x, while x is True checks for identity, which is different.

The bool() function is straightforward yet powerful, allowing Python to handle a variety of truthiness tests consistently across its rich ecosystem.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments