0

I have a problem. I'm learning Python now and I put this code in my IDE:

def get_gender(sex="Unknown"):
    sex = sex.lower()
    if sex is 'm':
        sex = 'Male'
    elif sex is 'f':
        sex = 'Female'
    print(sex)


get_gender()
get_gender("f")
get_gender("m")

I do not know why it doesn't print "Male" and "Female"

Why

"f".lower() 

is diffrent to

"f"

?

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

3

Your code is written based on the mistaken belief that is and == are equivalent in function and usage...

Your code should look like this...

def get_gender(sex="Unknown"):
    sex = sex.lower()
    if sex == 'm':                        # change 'is' to '=='
        sex = 'Male'
    elif sex == 'f':                      # change 'is' to '=='
        sex = 'Female'
    print(sex)

get_gender()
get_gender("f")
get_gender("m")

What went wrong...

is tests to see if two objects are the same object or not

== tests to see if two values are equivalent or not

When Python creates objects, they are provided with unique identifiers. Generically, is tests to see if the identifiers for two objects are the same, thus indicating that the objects are the same. In this case, the argument you provide to the function (i.e. 'm') is NOT the same object that you define in the function to compare against (i.e. the 'm' in the if sex is 'm' statement).

== tests to see if two objects have the same value.

E. Ducateme
  • 4,028
  • 2
  • 20
  • 30
  • could eliminate the assignment by converting it to lower during comparison as if sex.lower() == "m" – ayrusme Oct 07 '17 at 06:11
  • @thatrockbottomprogrammer you are right. In the interest of clarity, I opted to show why the problem occurred in deference to showing how to optimize the code for clarity/performance, etc. – E. Ducateme Oct 07 '17 at 06:16