Python 'If not' syntax

0 votes

I'm a bit confused about how/why so many python developers use if not in their conditional statements.

for example, lets say we had a function,

def foo(bar = None): if not bar: bar = 2

But why go about this way? I mean, wouldn't doing if bar != None or if bar is not Nonebe more explicit? What does if not try to say?

Aug 1, 2018 in Python by bug_seeker
• 15,320 points
40 views

1 answer to this question.

0 votes

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

answered Aug 1, 2018 by Priyaj
• 56,200 points

Related Questions In Python

0 votes
1 answer

Python if not == vs if !=

Using dis to look at the bytecode ...READ MORE

answered Jan 28 in Python by SDeb
• 13,160 points
63 views
0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12 in Python by Nymeria
• 3,500 points
52 views
0 votes
1 answer

How to get travis to fail if tests do not have enough coverage for python?

if you add the --fail-under switch to ...READ MORE

answered May 10 in Python by SDeb
• 13,160 points
34 views
0 votes
1 answer

Open a file if it exists or create and open it does not exists - Python

You can use this: f = open("ex.txt","w+") Here the ...READ MORE

answered Jun 20 in Python by Jason
17 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 169 views
+4 votes
6 answers
0 votes
1 answer

Python `if x is not None` or `if not x is None`?

There's no performance difference, as they compile ...READ MORE

answered Sep 3, 2018 in Python by Priyaj
• 56,200 points
170 views
+1 vote
1 answer

How to check if a string is null in python

Try this: if cookie and not cookie.isspace(): # the ...READ MORE

answered Aug 20, 2018 in Python by Priyaj
• 56,200 points
2,141 views