Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if statement: False vs. 0.0

Is it possible to:

for k,v in kwargs.items()
    if v == None or v == '' or v == 1.0 or v == False:
       del kwargs[k]

without deleting the key if v == 0.0? (False seems to equal 0.0), and without deleting the keys who equal True.

like image 527
Izz ad-Din Ruhulessin Avatar asked Oct 16 '10 12:10

Izz ad-Din Ruhulessin


People also ask

Is 0 the same as false in Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true.

Is 1 True or false Python?

Python Booleans as Numbers Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.

Does Python treat 0 as null?

Python uses the keyword None to define null objects and variables. While None does serve some of the same purposes as null in other languages, it's another beast entirely. As the null in Python, None is not defined to be 0 or any other value.

What is the integer equivalent to false in Python?

In Python 3. x True and False are keywords and will always be equal to 1 and 0 .


2 Answers

Or you can put it like this :

if v in (None, '', 1.0) or v is False:
like image 130
mouad Avatar answered Oct 14 '22 18:10

mouad


You should use v is False instead of v == False. The same applies for your comparison to None. See PEP 8 - Style Guide for Python:

Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.

like image 21
Mark Byers Avatar answered Oct 14 '22 18:10

Mark Byers