python
Check for falsy values - None, False, blank in Python
To check for falsy values like None, False, blank value in Python you can use methods explained in this post.
val1 = ''
if val1:
print("Not a falsy value")
else:
print("Falsy value")
# -> Falsy value
val2 = 'devsheet'
if val2:
print("Not a falsy value")
# -> Not a falsy value
We are checking falsy values here we are just placing Python variable after if statement and if the value is not falsy the block code inside if statement will be executed.
value = None
if value:
print('Value is not falsy')
else:
print('Value is falsy')
Output
Value is falsy
Check falsy values using bool() function
We can also use the bool() function to check for falsy values in Python. This function will return False for Falsy values and returns True for truth value. We can understand them using below code examples.
bool(['a', 'b', 'c'])
# -> True
bool([])
# -> False
bool(30)
# -> True
bool(0)
# -> False
bool(0.0)
# False
bool(-10)
# True
bool(True)
# -> True
bool(False)
# -> False
bool({'name': 'Rick', 'value': '30'})
# -> True
bool({})
# -> False
bool(None)
# -> False
bool(range(0))
# False
bool(set())
# False
if bool([]):
print('List is empty')
So we can check if a list is empty using the bool() function. The bool() function will return False if the given list is empty.
value = 10
if value not in ['', None]:
print('Value is not blank or none')
We are checking here if the value is not blank or None.
Was this helpful?
Similar Posts
- Python code to remove falsy values(None, False, [], {}, etc)
- Replace NULL with false while Selecting in SQLAlchemy
- Python check NaN values with and without using packages
- Evaluate,check before class feald values set, bothe constructor,property option
- Check if a column contains zero values only in Pandas DataFrame
- [Python] Function returns multiple values
- Get all values by key name from a list of dictionaries Python