1

let's assume that I have a resultset with a couple of fields. Now one of these fields is coming as 'NULL' or in Python language None. Now I need to create a method to replace whole Nones in a field by a specific word example 'UNKNOWN'. Here is my method.

def definegender(x):
    if x is not None:
      return x
    else:
        x = 'unknown'
        return x

Now testing

z= None
definegender(z)
print('{}'.format(z))

Unfortunately, my approach does not work, please can you guys let me know the best way to create this validation. Thanks

1
  • You cannot assign by reference in Python. Commented Jul 25, 2017 at 18:31

1 Answer 1

2

What you aim to do is assign by reference. Is some languages like C, C++ and C# that is possible. In Java and Python it is not. You can alter the state (if you for instance pass a list, you can update the elements, but you cannot set another list to it).

You can however use an assignment operator:

z = None
z = definegender(z)
print('{}'.format(z))

Furthermore you can make the code shorter by using a ternary operator in the definegender function:

def definegender(x):
    return x if x is not None else 'unknown'
Sign up to request clarification or add additional context in comments.

5 Comments

Hi buddy, when I try z = definegender(z) without a previous named i got this error NameError: name 'z' is not defined
@AndresAngel: of course you first have to make sure that z is initialized, like in your own code fragment.
Well i initialized as z= None but it didnt return 'unknown' :(
@AndresAngel: If I run it on my machine, z is 'undefined' after the call. Are you sure you set z to None and not to the string 'None'?
Awesome works like that!! z= None print(definegender(z))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.