Why can i use a short version of the code here?

Screen Link:

In the exercise five of “Cleaning and Preparing Data in Python” there is the following instruction:

  • Use an if statement to check if the value is an empty string. If the value is an empty string, give it the value "Gender Unknown/Other".

So i create the following code (which is correct, but…):

for row in moma:
    gender = row[5]
    gender = gender.title()
    if gender == "":
        gender = "Gender Unknown/Other"
    row[5] = gender

(…) in the solution code, there is only an “If not…” Statement.
Why can i use this short code?

for row in moma:
    # fix the capitalization and missing
    # values for the gender column
    gender = row[5]
    gender = gender.title()
    if not gender:
        gender = "Gender Unknown/Other"
    row[5] = gender

Hello @1sp34k2r0b0ts ,

The if not syntax is used to test boolean values. For example, let’s say you have a boolean variable called boolean and you want an if statement to check if it’s True or False:

boolean = True
if boolean:
    print('This is True')

Output:

‘This is True’

or…

boolean = False
if not boolean:
    print('This is False')

Output:

‘This is False’

With that said, empty strings along with other empty python objects are considered to be False, and that’s why you can use this syntax.

Read more in the link below:

https://docs.python.org/3/library/stdtypes.html#truth-value-testing

1 Like