Boolean Values with Python

Boolean Values

In Python, boolean values are used to represent truth values and are fundamental for conditional statements and logical operations. There are two boolean constants:

  • True: Represents truth or a condition that is met.
  • False: Represents falsity or a condition that is not met.

In Python, booleans are a subclass of integers, meaning they can be used as numbers where True is equivalent to 1 and False is equivalent to 0. 

a = True
b = False
print(type(a))  # Outputs: <class 'bool'>
print(type(b))  # Outputs: <class 'bool'>

Implicit and Explicit Conversion

Python performs automatic conversion between types in boolean contexts:

  • Implicit Conversion: Objects are automatically converted to booleans when used in conditional expressions. For instance, an empty list [], an empty string “”, or 0 are considered False. Any other value is considered True.
print(bool([]))  # Outputs: False
print(bool([1])) # Outputs: True
print(bool(""))  # Outputs: False
print(bool("non-empty"))  # Outputs: True
print(bool(0))   # Outputs: False
print(bool(1))   # Outputs: True
  • Explicit Conversion: You can use the bool() function to explicitly convert a value to a boolean.
print(bool("Hello"))  # Outputs: True
print(bool(None))     # Outputs: False
print(bool(3.14))     # Outputs: True
print(bool({}))       # Outputs: False
  1. Booleans as Integers

Since True and False are subclasses of int, you can use them in mathematical operations.

  • True is equivalent to 1
  • False is equivalent to 0
print(True + 1)  # Outputs: 2
print(False + 10) # Outputs: 10
print(True * 10) # Outputs: 10
print(False * 10) # Outputs: 0

Booleans in Comparisons

Boolean values result from comparison operations:

  • Equality: ==
  • Inequality: !=
  • Greater Than: >
  • Less Than: <
  • Greater Than or Equal To: >=
  • Less Than or Equal To: <=

These operators compare two values and return True or False. 

a = 5
b = 10
print(a == b)   # Outputs: False
print(a != b)   # Outputs: True
print(a > b)    # Outputs: False
print(a < b)    # Outputs: True
print(a >= b)   # Outputs: False
print(a <= b)   # Outputs: True

Booleans in Control Structures

Booleans are used to control the flow of execution in conditional statements like if, while, and for loops.

if Statement

The if statement uses boolean expressions to determine whether to execute a block of code. 

x = 20
if x > 10:
    print("x is greater than 10")
else:
    print("x is 10 or less")

while Loop

The while loop continues to execute as long as the condition is True. 

counter = 0
while counter < 5:
    print(counter)
    counter += 1

for Loop

The for loop iterates over iterable sequences, and the boolean condition for each item is implicitly checked. 

for i in range(5):
    print(i)

Boolean Operators

Boolean operators allow you to combine multiple conditions. They are used in boolean expressions to form complex conditions.

  • and: Returns True if both conditions are true.
a = True
b = False
print(a and b)  # Outputs: False
print(a and not b)  # Outputs: True
  • or: Returns True if at least one condition is true. 
print(a or b)  # Outputs: True
print(not a or b)  # Outputs: False
  • not: Returns the inverse of the condition.
print(not a)  # Outputs: False
print(not b)  # Outputs: True

Truth Value Testing

Some values are tested as False in boolean contexts. These include:

  • None
  • 0 (zero of any numeric type)
  • 0.0
  • ” (empty string)
  • [] (empty list)
  • {} (empty dictionary)

All other values are tested as True. 

def check_value(val):
    if not val:
        print("The value is equivalent to False")
    else:
        print("The value is equivalent to True")
check_value([])   # Outputs: The value is equivalent to False
check_value([1])  # Outputs: The value is equivalent to True
check_value(0)    # Outputs: The value is equivalent to False
check_value(1)    # Outputs: The value is equivalent to True

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print