The following piece of code works fine.
a = 2.0
b = int(a)
And b
is 2
.
But the following does not work:
a = None
b = int(a)
I get the following error:
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
This works:
a = None
if a != None:
b = int(a)
else:
b = 0
But it is too much code because I have several such variables in my use case that can be None.
What I want:
- b = a, if a is not None.
- b = 0, if a is None
Is there an elegant way of doing this with a built in function or something that I am not aware of the existence of...?
CodePudding user response:
If you need to try this a bunch of times, you could make a very small function with a try:...except:...
block.
def try_int(v):
try:
return int(v)
except TypeError:
return 0
a = 2
b = try_int(a) # should return 2
c = None
d = try_int(c) # should return 0
This solution sticks to the principal of 'asking for forgiveness, not permission' and also not repeating yourself by having a bunch of separate try:...except:...
blocks and instead just the one.
CodePudding user response:
Just a short way: b = int(a or 0)