Use not Operator
In Python, the not
operator is a logical operator that negates the boolean value of its operand. It returns True
if the operand is False
, and False
if the operand is True
. This is particularly useful when you want to check if a value is falsy.
Let's modify the falsy_values.py
script from the previous step to use the not
operator.
-
Open the falsy_values.py
file in your WebIDE.
-
Modify the script to include the not
operator:
## falsy_values.py
falsy_values = [False, None, 0, 0.0, '', [], {}, ()]
for value in falsy_values:
if not value:
print(f"{value} is falsy")
else:
print(f"{value} is truthy")
In this modified script, the if not value:
condition checks if the value is falsy. If value
is falsy, not value
evaluates to True
, and the code inside the if
block is executed. Otherwise, if value
is truthy, not value
evaluates to False
, and the code inside the else
block is executed.
To run the script, open a terminal in your WebIDE (if you don't see one, click "Terminal" -> "New Terminal"). Then, execute the following command:
python falsy_values.py
You should see the following output:
False is falsy
None is falsy
0 is falsy
0.0 is falsy
is falsy
[] is falsy
{} is falsy
() is falsy
The output is the same as in the previous step, but now we are using the not
operator to explicitly check for falsy values. This can make your code more readable and easier to understand.