The Boolean data type in Python is among the built-in data types. It serves the purpose of indicating the truth value of a given expression. For instance, the expression 3 <= 5 evaluates to True, whereas the expression 2 == 4 evaluates to False.
Python Boolean Type
In Python, the Boolean data type can take on only two distinct values:
- True
- False
The variables classified under the Boolean data type are part of the 'bool' class, illustrated in the example below:
Example
# Python Boolean type example
# defining and initializing the variables
x = True
y = False
# printing the data type of the variables
print(x, "->", type(x))
print(y, "->", type(y))
Output:
True -> <class 'bool'>
False -> <class 'bool'>
Explanation:
In this instance, we have set up several variables with Boolean values (True and False) and utilized the type function to identify their types. Consequently, these variables are classified under the 'bool' class.
Note: The variable initialized with Boolean values must be capitalized. The lowercase values such as true or false will raise a NameError exception.
Evaluating Variables and Expressions
The assessment of variables and their corresponding values can be accomplished utilizing the Python bool function. This particular function enables the transformation of a value into a Boolean value—either True or False—by employing the conventional method of truth testing.
Python bool Function
In Python, the bool function serves to transform a given value or expression into its equivalent Boolean representation, which can be either True or False. Below is the syntax for this function:
Syntax:
bool(value)
In this context, the 'value' argument can represent any Python object that requires conversion to a Boolean type. If this argument is not provided, the function will automatically default to a value of False.
Let’s examine a straightforward illustration presented below:
Example
# Python example to show the use of the bool() function
# numbers
print("0 ->", bool(0)) # Returns False as value is 0
print("0.0 ->", bool(0.0)) # Returns False as value is 0.0 (float)
print("1 ->", bool(1))
print("-5 ->", bool(-5))
# strings
print("'' ->", bool('')) # # Returns False as value is an empty string
print("'Example' ->", bool('Example'))
# lists
print("[] ->", bool([])) # Returns False as value is an empty list
print("[11, 12, 13] ->", bool([11, 12, 13]))
# tuples
print("() ->", bool(())) # Returns False as value is an empty tuple
print("(11, 12, 13) ->", bool((11, 12, 13)))
# sets
print("{} ->", bool({})) # Returns False as value is an empty set
print("{11, 12, 13} ->", bool({11, 12, 13}))
# None
print("None ->", bool(None)) # Returns False as value is None
Output:
0 -> False
0.0 -> False
1 -> True
-5 -> True
'' -> False
'Example' -> True
[] -> False
[11, 12, 13] -> True
() -> False
(11, 12, 13) -> True
{} -> False
{11, 12, 13} -> True
None -> False
Explanation:
In the preceding example, the bool function has been utilized to transform specified values across various data types, including numbers, strings, lists, tuples, sets, and None types, into their respective Boolean representations. Consequently, numerical values like 0 and 0.0, in addition to empty sequences and the None type, yield False, whereas all other values are converted to True accordingly.
Boolean Operators in Python
In Python, Boolean operators facilitate logical operations on Boolean expressions. They yield either True or False based on the underlying logical relationships.
In Python, there are primarily three Boolean operators:
| Operator | Name | Description |
|---|---|---|
and |
Boolean AND | This operator returns True if both operands are true. |
or |
Boolean OR | This operator returns True if at least one operand is true. |
not |
Boolean NOT | This operator reverses the Boolean value. |
Let us understand the following these operators with the help of examples.
Boolean AND Operator
The Boolean AND Operator yields a True result when both operands evaluate to true. Conversely, if either of the inputs is false, the expression will result in False.
The truth table below illustrates the functionality of the AND operator:
| A | B | A and B |
|---|---|---|
True |
True | True |
True |
False | False |
| False | True | False |
| False | False | False |
The following is a simple example of the Boolean AND Operator:
Example
# Python program to show Boolean AND operator
# printing results
print("True and True =>", True and True)
print("True and False =>", True and False)
print("False and True =>", False and True)
print("False and False =>", False and False)
print("5 > 2 and -4 < 0 =>", 5 > 2 and -4 < 0)
print("0 > 1 and 6 < 8 =>", 0 > 1 and 6 < 8)
Output:
True and True => True
True and False => False
False and True => False
False and False => False
5 > 2 and -4 < 0 => True
0 > 1 and 6 < 8 => False
Explanation:
In this instance, we have executed multiple operations utilizing the AND operator. This illustration demonstrates that the Boolean AND operator yields True exclusively when both conditions are satisfied; in all other cases, it results in False.
Boolean OR Operator
The Boolean OR operator yields a True result if at least one of the operands evaluates to true. Conversely, if both operands are false, the outcome will be False.
The truth table below illustrates the functionality of the OR operator:
| A | B | A or B |
|---|---|---|
True |
True | True |
True |
False | True |
| False | True | True |
| False | False | False |
The following is a simple example of the Boolean OR Operator:
Example
# Python program to show Boolean OR operator
# printing results
print("True or True =>", True or True)
print("True or False =>", True or False)
print("False or True =>", False or True)
print("False or False =>", False or False)
print("-4 > 2 or -7 < 0 =>", -4 > 2 or -7 < 0)
print("4 > 6 or 9 < 4 =>", 4 > 6 or 9 < 4)
Output:
True or True => True
True or False => True
False or True => True
False or False => False
-4 > 2 or -7 < 0 => True
4 > 6 or 9 < 4 => False
Explanation:
In the preceding example, we conducted a series of operations utilizing the OR operator. In this instance, it is evident that the Boolean OR operator yields True if at least one of the specified conditions evaluates to true. Conversely, it produces False solely when both conditions are false.
Boolean NOT Operator
The Boolean NOT operator is a type of Boolean operator that takes a single argument (or operand) and produces its negation. In other words, this operator will yield True when the argument is False, and it will return False when the argument is True.
The truth table below illustrates the functionality of the NOT operator:
| A | not A |
|---|---|
True |
False |
| False | True |
Let us see a simple example of the NOT operator in Python
Example
# Python program to show Boolean NOT operator
# printing results
print("not 0 =>", not 0)
print("not (6 > 1) =>", not (6 > 1))
print("not True =>", not True)
print("not False =>", not False)
Output:
not 0 => True
not (6 > 1) => False
not True => False
not False => True
Explanation:
In this illustration, we can see that the Boolean NOT operator has inverted the truth value of the specified operands. Consequently, it yields False for expressions that are true and True for those that are false.
Boolean Equality (==) and Inequality (!=) Operators in Python
In Python, the equality operator (==) and the inequality operator (!=) serve to compare values, assessing whether they are equal or not. The outcome of these comparisons yields a Boolean result, which can be either True or False, depending on the evaluation of the values involved.
The equality operator (==) is used to determine whether two values are identical. When the values match, this operator yields True; if they do not match, it returns False.
The inequality operator (!=) is utilized to determine whether two values are distinct from one another. When the values are not equal, this operator yields True; conversely, it returns False if the values are equal.
Let’s examine an illustration that demonstrates the functionality of these operators in Python.
Example
# Python program to show Boolean Equality and Inequality operators
# equality (==) operator
print("(8 == 8) =>", 8 == 8)
print("(True == 1) =>", True == 1) # since non-zero value is considered as True
print("(False == 0) =>", False == 0) # 0 is considered as False
print("(6 == -4) =>", 6 == -4)
print()
# inequality (!=) operator
print("(8 != 6) =>", 8 != 6)
print("(True != 1) =>", True != 1)
print("(False != 0) =>", False != 0)
print("(4 != 4) =>", 4 != 4)
Output:
8 == 8) => True
(True == 1) => True
(False == 0) => True
(6 == -4) => False
(8 != 6) => True
(True != 1) => False
(False != 0) => False
(4 != 4) => False
Explanation:
In this instance, we can see that the equality operator yields True when the two values are identical, whereas the inequality operator gives True when the values differ.
Python 'is' Operator
In Python, the 'is' operator serves the purpose of determining whether two variables reference the identical object in memory. It is important to note that this operator does not assess whether the values of the variables are equivalent.
Below is an illustration demonstrating the application of the 'is' operator in Python:
Example
# Python program to show 'is' operator
# initializing variables
a = [13, 26, 39]
b = a
c = [13, 26, 39]
# checking identities of the variables
print("a is b =>", a is b)
print("a is c =>", a is c)
Output:
a is b => True
a is c => False
Explanation:
In the scenario where a is b, the 'is' operator yields True because both variables reference the identical object. Conversely, for a is c, it produces False since the two variables reference distinct objects that hold the same value.
Python 'in' Operator
In Python, the 'in' keyword serves the purpose of verifying if a particular value is present within a container, which can include data structures like lists, tuples, strings, dictionaries, or sets.
Let’s consider an illustration of the 'in' operator in Python.
Example
# Python program to show 'is' operator
# initializing variables
int_list = [12, 17, 23, 34, 41] # list
fruits = {'apple', 'plum', 'mango'} # set
sample_str = 'logicpractice' # string
# checking elements in given list
print("17 in int_list =>", 17 in int_list)
print("19 in int_list =>", 19 in int_list)
print()
# checking items in given set
print("apple in fruits =>", 'apple' in fruits)
print("banana in fruits =>", 'banana' in fruits)
print()
# checking letter in given string
print("t in sample_str =>", 't' in sample_str)
print("q in sample_str =>", 'q' in sample_str)
Output:
17 in int_list => True
19 in int_list => False
apple in fruits => True
banana in fruits => False
t in sample_str => True
q in sample_str => False
Explanation:
In the example provided, we can see that the 'in' operator functions to determine whether a specific element is present within a list, set, or string. Consequently, it yields True if the element is located and False if it is not.
Conclusion
In Python, Booleans denote truth values with True and False, playing a crucial role in decision-making processes within code. By utilizing Boolean operators such as and, or, and not, we can construct logical expressions effectively. Additionally, Python incorporates other comparison operators including in, is, ==, and !=, which further emphasizes the significance of Boolean logic in crafting clear and efficient programs.
Python Boolean MCQs
- What will the result of executing the following code be?
# python program
print(bool([]))
- True
- False
- None
- Error
Response: b) Incorrect
- Which operator yields True exclusively when both conditions hold True?
- What does the 'is' operator check?
- If two values are equal
- If two values are of the same type
- If two variables point the same object
- If a variable exists
Response: c) When two variables reference the identical object
- What will the result be from executing the subsequent code?
# python program
print(not (5 > 2 or 3 < 1))
- True
- False
- Error
- None
- Which of the following will return True?
- 5 != 5
- is
- bool(0)
- 'p' in 'purple'