Value and Variable Evaluation in Python

Value and Variable Evaluation in Python

Boolean Contexts

In Python, certain values and variables are evaluated in a boolean context, such as in conditional statements (if, while, etc.), logical operations, or when converting to booleans using the bool() function. Understanding how different values evaluate to True or False is crucial for writing correct and efficient code.

Truthiness and Falsiness

Python determines the boolean value of an object based on its “truthiness” or “falsiness.” Here are the general rules:

  • Falsy Values: These are values that evaluate to False in a boolean context. The most common falsy values are:
    • None
    • False itself
    • 0 (zero of any numeric type, including 0.0 for floats)
    • ” (empty string)
    • [] (empty list)
    • {} (empty dictionary)
    • set() (empty set)

Example:

def check_value(val):
    if not val:
        print("The value is falsy")
    else:
       print("The value is truthy")
check_value(None)  # Outputs: The value is falsy
check_value('')    # Outputs: The value is falsy
check_value([])    # Outputs: The value is falsy
check_value(0)     # Outputs: The value is falsy
  • Truthy Values: Any value that is not falsy is considered truthy. This includes:
    • Non-empty strings: ‘hello’, ‘ ‘
    • Non-zero numbers: 1, -1, 3.14
    • Non-empty collections: [1], {‘key’: ‘value’}, set([1])

Example: 

check_value('hello')   # Outputs: The value is truthy
check_value([1])       # Outputs: The value is truthy
check_value(1)         # Outputs: The value is truthy

Evaluating Variables

When you use variables in a boolean context, their truthiness is determined by the value they hold. For instance: 

var1 = [1, 2, 3]
var2 = []
if var1:
    print("var1 is truthy")  # This will print because var1 is a non-empty list.
else:
    print("var1 is falsy")
if var2:
    print("var2 is truthy")
else:
    print("var2 is falsy")  # This will print because var2 is an empty list.

Boolean Operations with Variables

Boolean operations (and, or, not) can be used to combine and manipulate boolean expressions. Understanding how these operations work with variables can help you write more effective conditions.

  • and Operator: Returns True if both operands are true. If the first operand is false, it returns the first operand; otherwise, it returns the second operand.
a = True
b = False
print(a and b)  # Outputs: False
print(b and a)  # Outputs: False
print(a and True)  # Outputs: True
  • or Operator: Returns True if at least one of the operands is true. If the first operand is true, it returns the first operand; otherwise, it returns the second operand.
a = True
b = False
print(a or b)  # Outputs: True
print(b or a)  # Outputs: True
print(False or False)  # Outputs: False
  • not Operator: Inverts the boolean value of its operand. 
a = True
b = False
print(not a)  # Outputs: False
print(not b)  # Outputs: Tru

Short-Circuit Evaluation

Python uses short-circuit evaluation for boolean operations. This means that in an and operation, if the first operand is falsy, Python does not evaluate the second operand. In an or operation, if the first operand is truthy, Python does not evaluate the second operand.

  • Short-Circuit with and:
def check_a():
    print("Checking A")
    return False
def check_b():
    print("Checking B")
    return True
result = check_a() and check_b()
# Outputs: Checking A
# `check_b()` is not called because `check_a()` returned False
  • Short-Circuit with or
def check_x():
    print("Checking X")
    return True
def check_y():
    print("Checking Y")
    return False
result = check_x() or check_y()
# Outputs: Checking X
# `check_y()` is not called because `check_x()` returned Tru

Custom Boolean Contexts

Custom objects can define their truthiness by implementing the __bool__() (or __nonzero__() in Python 2) method. This method should return True or False depending on the state of the object.

  • Example:
class CustomObject:
    def __init__(self, value):
        self.value = value
    def __bool__(self):
        return self.value > 0
obj1 = CustomObject(10)
obj2 = CustomObject(0)
print(bool(obj1))  # Outputs: True
print(bool(obj2))  # Outputs: False

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