I was given a Python test and one of the questions was: what should be passed to the following function, so that it will return True
?
def fun(x):
if x + 1 is 1 + x:
return False
if x + 2 is not 2 + x:
return False
return True
In my opinion this doesn't make much sense but I just would like to know the right answer (if such answer exists).
This has to do with how python caches small numbers: https://stackoverflow.com/a/48120163/13003236
Typically, is
is used to check if two variables are the same object instead of if they have the same value. However, because of how python caches small numbers, calling is
on numbers from -5 to 256 has the same effect as comparing them. So, this function returns true if x + 1
is less than -5, but x + 2
is greater than or equal to -5. That means that passing -7 into this function will cause it to succeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With