Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python None and if conditions

Tags:

python

I have some code here:

m = None
n = None

if not m:
    print "Something happens"
>>> Something happens

if I do:

if not m and n:
    print "Something happens"

Nothing happens.

But I can do:

m, n = 1,2
if m and n:
    print "Something happens"
>>> Something happens

Why are if and if not handled the same way? Does 'if not', not take 'and' statements?

Thank you

like image 845
Neeran Avatar asked Dec 03 '22 04:12

Neeran


1 Answers

You have an operator precedence problem.

if not m and n is equivalent to if (not m) and n. What you want is if not m and not n or if not (m or n).

See also: De Morgan's Laws

like image 55
jtbandes Avatar answered Dec 05 '22 17:12

jtbandes