How to convert Nonetype to int or string?

Viewed 363154

I've got an Nonetype value x, it's generally a number, but could be None. I want to divide it by a number, but Python raises:

TypeError: int() argument must be a string or a number, not 'NoneType'

How can I solve this?

10 Answers

In Python 3 you can use the "or" keyword too. This way:

foo = bar or 0
foo2 = bar or ""

In some situations it is helpful to have a function to convert None to int zero:

def nz(value):

    '''
    Convert None to int zero else return value.
    '''

    if value == None:
        return 0
    return value
Related