Question
Asked By – user469652
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?
Now we will see solution for issue: How to convert Nonetype to int or string?
Answer
In one of the comments, you say:
Somehow I got an Nonetype value, it supposed to be an int, but it’s now a Nonetype object
If it’s your code, figure out how you’re getting None
when you expect a number and stop that from happening.
If it’s someone else’s code, find out the conditions under which it gives None
and determine a sensible value to use for that, with the usual conditional code:
result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
…or even…
if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.
There’s no reason to automatically use 0
here — solutions that depend on the “false”-ness of None
assume you will want this. The DEFAULT_VALUE
(if it even exists) completely depends on your code’s purpose.
This question is answered By – detly
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0