Truthy vs Falsy Values
In Python, individual values can evaluate to either True or False.
The Basis rules are:
- Values that evaluate to False are considered Falsy.
- Values that evaluate to True are considered Truthy.
Falsy Values Includes:
1) Sequences and Collections:
- Empty lists []
- Empty tuples ()
- Empty dictionaries {}
- Empty sets set()
- Empty strings ” “
- Empty ranges range(0)
2) Numbers: Zero of any numeric type.
- Integer: 0
- Float: 0.0
- Complex: 0j
3) Constants:
- None
- False
Falsy values were the reason why there was no output in our initial example when the value of number was zero.
Truthy Values Includes:
- Non-empty sequences or collections (lists, tuples, strings, dictionaries, sets).
- Numeric values that are not zero.
- Constant: True
This is why the value of a printed in our initial example because its value of a number was 7(a truthy value):
Truthy vs Falsy Values in Python
In this article, we will see about the concept of Truthy and Falsy values in Python and also see how to determine a value is Truthy or Falsy by using bool() built-in Python function.
Now, Let’s start with the following two codes:
Python3
number = 7 if number: print (number) |
Output:
7
Let’s change value of number to 0
Python3
number = 0 if number: print (number) |
Output:
There is no Output
Have you wondered why the above code run successfully despite number not being an expression?
The answer lies in concept of Truthy and Falsy Values.
Contact Us