As a beginner developer, you often come across codes like this in conditional statements:
if value:
print("Value exists!")
At first, it can be confusing to understand what the simple if value:
statement is checking.
Especially the two below:
None
""
(empty string)
Both of these are evaluated as False
, which makes them feel similar.
But is that really the case?
Falsy Values
In Python, the following values are evaluated as False in conditional statements:
None
False
0
,0.0
""
(empty string)[]
(empty list){}
(empty dictionary)set()
,()
and other empty collections
Therefore, if not value:
captures all of these at once.
None
and ""
Are Different
These two look different and behave differently.
value1 = None
value2 = ""
print(value1 == value2) # False
print(value1 is value2) # False
print(bool(value1)) # False
print(bool(value2)) # False
==
checks value equality whileis
checks identity.None
is a special object that means “there is no value yet”,- whereas
""
is a string that is empty.
In the image above, the man on the left holds a speech bubble but says nothing — this corresponds to the empty string ""
.
The woman on the right has no speech bubble at all — this corresponds to None
.
Both of these are evaluated as False
under the following condition:
male_voice = ""
female_voice = None
if not male_voice and not female_voice:
print("Both say nothing!") # Executes as both are False
So how do we distinguish in practice?
For instance, let’s look at handling user input:
username = user_input.get("username", None)
- If the user didn’t input anything →
None
- If the user input an empty string →
""
If you want to handle these differently?
if username is None:
print("No input at all!")
elif username == "":
print("You entered an empty string.")
else:
print("Entered value:", username)
Common Mistakes in Practice
The following code sometimes unintentionally filters out all Falsy values:
if not username:
print("No input provided")
However, this condition includes not only empty strings but also None
, 0
, empty lists, etc.
Thus, intentions need to be made clear:
- Even if empty, a string should be allowed →
if username is None:
- A string should exist but can be empty →
if username != "":
- There should be no value at all →
if not username:
In Conclusion
None
and ""
are not the same. However, both behave like False
.
Understanding this difference will allow your code to be more clear and free of bugs.
In the next post, I will delve deeper into other Falsy values like 0
, []
, {}
and explore the differences between is
and ==
!
Add a New Comment