Hướng dẫn compare with none python
My editor warns me when I compare Show I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that Is this the case, and if so, why?
Mad Physicist 100k24 gold badges163 silver badges244 bronze badges asked Jan 9, 2013 at 22:06
Clay WardellClay Wardell 13.8k11 gold badges42 silver badges63 bronze badges 3 Summary:Use Explanation:You can have custom classes where e.g:
In other words,
answered Jan 9, 2013 at 22:08
13
This recommendation is supported by PEP 8, which
explicitly states that "comparisons to singletons like None should always be done with
Chris 6,7473 gold badges53 silver badges80 bronze badges answered Jan 9, 2013 at 22:10
user4815162342user4815162342 129k15 gold badges253 silver badges315 bronze badges 5 PEP 8 defines that it is better to use the
halfelf 9,19913 gold badges50 silver badges62 bronze badges answered Jan 9, 2013 at 22:11
Thorsten KranzThorsten Kranz 12.1k2 gold badges38 silver badges55 bronze badges 2 I recently encountered where this can go wrong.
I created a function that optionally takes a numpy array as argument and changes if it is included. If I test for its inclusion using inequality operators answered Apr 9, 2021 at 14:15
DanfernoDanferno 4264 silver badges9 bronze badges 2 A useful tidbit to add to people's understanding. The reason that we check for
identity with But most values do not get this special treatment! For example, the float 1.25 can be stored in different locations in memory:
True
False It just so happens that
True
False So you can think of Edit: Joooeey makes the good point that which integers are stored in memory is specific to your python implementation, and the example of numbers from answered Aug 3 at 13:12
doublefelixdoublefelix 8451 gold badge8 silver badges20 bronze badges 1 Another instance where "==" differs from "is". When you pull information from a database and check if a value exists, the result will be either a value or None. Look at the if and else below. Only "is" works when the database returns "None". If you put == instead, the if statement won't work, it will go straight to else, even though the result is "None". Hopefully, I am making myself clear.
answered Jun 26, 2021 at 23:08 We can take the list for example. Look here:
All have the same value:
Now we get the desired result.
PEP 8 also mentions this, saying "comparisons to singletons like None should always be done with is or is not, never the equality operators."
answered May 18, 2021 at 19:15
Aarav DaveAarav Dave 811 silver badge7 bronze badges 6 Not the answer you're looking for? Browse other questions tagged python comparison nonetype or ask your own question. |