LIMITED TIME OFFER: 50% OFF OF PREMIUM WITH OUR ANNUAL PLAN (THAT'S $294 IN SAVINGS).
GET OFFER

5/10 Cleaning and Preparing Data in Python

Screen Link:

My Code:

for row in moma:
    gender = row[5]

    # convert the gender to title case
    gender = gender.title()

    # if there is no gender, set
    # a descriptive value
    if not gender:
        gender = "Gender Unknown/Other"
    row[5] = gender

What I expected to happen:

What actually happened:

Replace this line with the output/error

Can someone tell me what is the role of “if not gender:” part. Does this method only check empty string? Please elaborate the role of “not” here.

Yes, that’s correct. This is also explained in the content right above the code -

Use an if statement to check if the value is an empty string and, if so, give it a descriptive value.

It checks if gender is an empty string or not. It is an empty string, a descriptive value is assigned to it.

In Python, you can use not to see if a string datatype is empty or not. It is like the logical operators or or and. It checks if something is not True.

1 Like

the meaning of your code if not gender => if gender is null
it’s the easiest explanation of if not gender , by that you’ll understand your code.

if no just let me know.
Happy learning :sunglasses:.

1 Like

Can I use Not to check whether a list or tuple is empty?

Good question. I would recommend that you also consider testing your own ideas whenever possible. For example, for this, you can try to code something like the following -

a = []

b = ()

if not a:
    print("a is an empty list")
    
if not b:
    print("b is an empty tuple")

and you should get your answer when you run the code :slight_smile:

1 Like

Got it. I have one other question. If by “if not gender:” we can check whether the string is empty, can we use “if gender:” to use a condition that works only when the string is full? I tried it and it worked. Don’t know whether it is the right thing to do. Thank you so much for your insight.

1 Like

It is the right thing to do, but you have to be slightly careful by what you mean by “string is full”. Because if you add a space there, then that string is not considered empty by Python.

1 Like