0

All the time I tried to compare two variables with type None but it doesn't work.

example:

if type(a and b) == type(None): #do something else: #do other stuff 

Does somebody know the right statement and an explanation?

2
  • 4
    if a is None and b is None... Commented Apr 1, 2019 at 9:14
  • In case you need to check more than 2 variables, you could put them in an iterable and then check if all items in the list are None. Commented Apr 1, 2019 at 9:21

3 Answers 3

2

You can check differently.

if a is None and b is None: print('Both a and b are None') else: print('a and b are not None') 

Issues with your code.

  1. a and b will return either a or b
  2. type comparison is not a good option.
Sign up to request clarification or add additional context in comments.

1 Comment

To be precise, a and b will return either a or b.
0

In Python, if you want to check for null variables, you should use the x is None syntax. There is only one instance of the None object in a Python runtime (it's called a singleton). Moreover, checking against type tends to be bad practice in general. In your case, you should do:

if a is None and b is None: #do something else: #do other stuff 

You can also simplify it to if (a and b) is None, since the and operator will propagate the None if one of a and b is None.

Comments

0
def nonetype_check1(a,b): if a==b and a==None: print(" both are nonetype type",type(a)) elif a!=b: print("values of both are not same",a,b) else: print("values of both are same but not nonetype",type(b),type(b)) 

output: 1)a=Nonetype,b=Nonetype,answer:both are nonetype type 2)a=Nonetype,b=3, answer:values of both are not same None 3 3)a=3,b=3, answer:values of both are same but not nonetype

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.