Python Boolean (original) (raw)
Boolean is a built-in data type that represents only two values: True and False. It is commonly used to check conditions and represent the truth value of expressions in a program.
Python `
a = True print(type(a))
b = False print(type(b))
`
Output
<class 'bool'> <class 'bool'>
Evaluate Variables and Expressions
We can check or convert values into Boolean form using the bool() function. It returns either True or False based on the value of the expression.
**1. bool() Function: converts any value or expression into its corresponding Boolean value.
Python `
x = None print(bool(x))
x = () print(bool(x))
x = {} print(bool(x))
x = 0.0 print(bool(x))
x = 'GeeksforGeeks' print(bool(x))
`
Output
False False False False True
**Explanation: Empty values like None, (), {} and 0 are treated as False and non-empty strings or values are treated as True.
**Note: Python automatically evaluates values as True or False in conditions like if statements, so using bool() explicitly is not always required.
**2. Integers and Floats: numbers can also behave like Boolean values. Zero is considered False, while any non-zero number is considered True.
Python `
a = 0 print(bool(a))
b = 1 print(bool(b))
c = -9.7 print(bool(c))
`
Boolean Operators
Boolean operators are used to perform logical operations on True and False values. These operators help in decision-making in programs.
**1. OR Operator: returns True if at least one condition is True.
Python `
a = 5 b = 3 c = 8
if a > b or b < c: print("True")
`
**Explanation:
- a > b is True (5 > 3)
- b < c is True (3 < 8)
- Since at least one condition is True, the result is True.
**2. AND Operator: returns True only if all conditions are True, otherwise it returns False.
Python `
a = 0 b = 2 c = 4
if a > b and b < c: print(True) else: print(False)
if a and b and c: print("True") else: print("False")
`
**Explanation:
- First condition fails because a > b is False.
- 0 is treated as False, so a and b and c also becomes False.
**3. NOT Operator: reverses the Boolean value of an expression.
Python `
a = 0 if not a: print("False")
`
**Explanation: 0 is considered False, not False becomes True, so the condition executes.
**4. Equality Operators (== and !=): == operator returns True if both values are equal, while the != operator returns True if the values are not equal.
Python `
a = 0 b = 1
if a == 0: print(True)
if a == b: print(True)
if a != b: print(True)
`
**Explanation:
- a == 0 is True.
- a == b is False, so nothing prints.
- a != b is True.
**5. Identity Operator (is): checks whether two variables refer to the same object in memory.
Python `
x = 10 y = 10
if x is y: print(True)
`
**Explanation: Both variables refer to the same memory object, so x is y is True.
**6. Membership Operator (in): checks whether a value exists inside a sequence like a list, tuple, or string.
Python `
a = [1, 2, 2]
if 1 in a: print(True)
`
**Explanation: 1 is present in the list, so the condition becomes True.