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
• 14,980 points
32 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,140 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
• 10,700 points
61 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
18 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
• 10,700 points
9 views
0 votes
1 answer

'python' is not recognized as an internal or external command

I have met same issue when I ...READ MORE

answered Aug 24, 2018 in Python by Priyaj
• 56,140 points
77 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
54 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,140 points
119 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,140 points
1,040 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.