Monday, 22 January 2024

"Truthy" And "Falsey" values in Python

Python uses a special concept called truthy and falsy values. Truthy and Falsey values are different from the usual True and False, they describe how certain values behave in conditional statements and expressions.

Truthy values

These values are considered True in a Boolean context. Typical examples of truthy values are:

 

1.   Any number that isn't 0, whether it's positive, negative, an integer, or a float.

2.   Strings that aren't empty, even if they have just spaces or a single character.

3.   Non-empty collections, like lists, tuples, dictionaries, and sets.

4.   Specific built-in objects, including None and True.

 

Falsey values

These values are considered False in a Boolean context. Common examples of falsy values include:

 

1.   The number 0, whether as an integer or a float.

2.   An empty string, denoted as "".

3.   Empty collections, such as lists, tuples, dictionaries, and sets that have no elements.

4.   The None value, except when it's explicitly checked using "is None".

5.   The Boolean value False.

 

truthy_and_falsey_values.py

def demo(a):
    if a:
        print(f'{a} is evaluated to True')
    else:
        print(f'{a} is evaluated to False')

demo(0)
demo(0.0)
demo(1)

demo('')
demo('  ')

demo([])
demo([2, 3])

demo({})
demo({'x' : 123})

demo(None)
demo(True)

 

Output

0 is evaluated to False
0.0 is evaluated to False
1 is evaluated to True
 is evaluated to False
   is evaluated to True
[] is evaluated to False
[2, 3] is evaluated to True
{} is evaluated to False
{'x': 123} is evaluated to True
None is evaluated to False
True is evaluated to True

 


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment