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…?
>Solution :
Just a short way: b = int(a or 0)