“True” Keyword in Python: Understanding Boolean Values

"True" Keyword in Python: Understanding Boolean Values

Boolean values are data values that represent true or false conditions. In Python, Boolean values are denoted by the two keywords True and False. Boolean values are the simplest data types in Python, but they are crucial for decision-making in control structures.

Boolean Operations

Python provides three Boolean operations:

  1. and
  2. or
  3. not

The and operator returns True if both operands are True. It returns False otherwise. The or operator returns True if at least one operand is True. It returns False otherwise. The not operator returns True if its operand is False, and vice versa.

Using the and Operator

The following example illustrates the use of the and operator:

a = True
b = False
c = True

print(a and b) # Output: False
print(a and c) # Output: True

Using the or Operator

The following example illustrates the use of the or operator:

a = True
b = False
c = True

print(a or b) # Output: True
print(b or c) # Output: True

Using the not Operator

The following example illustrates the use of the not operator:

a = True
b = False

print(not a) # Output: False
print(not b) # Output: True

Truthy and Falsy Values

The following values are considered False in Python:

  • False
  • None
  • 0
  • 0.0
  • ""
  • ()
  • []
  • {}

All other values in Python are considered True. These values are known as truthy values. The following example illustrates this:

a = True
b = False
c = None
d = 0
e = 0.0
f = ""
g = ()
h = []
i = {}

if a:
    print("a is truthy.")

if not b:
    print("b is falsy.")

if not c:
    print("c is falsy.")

if not d:
    print("d is falsy.")

if not e:
    print("e is falsy.")

if not f:
    print("f is falsy.")

if not g:
    print("g is falsy.")

if not h:
    print("h is falsy.")

if not i:
    print("i is falsy.")

The output of the above code is as follows:

a is truthy.
b is falsy.
c is falsy.
d is falsy.
e is falsy.
f is falsy.
g is falsy.
h is falsy.
i is falsy.

Conclusion

The True keyword in Python represents the Boolean value True. It is used by the interpreter as one of the two possible values of a Boolean variable. In addition to the True and False values, Python also supports logical operations (and, or, and not) on Boolean values. Understanding Boolean values is essential for writing decision-making code in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *