Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a value is None and save to another variable only if it is not None in Python

The following piece of code works fine.

a = 2.0
b = int(a)

And b is 2.

But the following does not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading