Why are different results from if statement in Python 3 and C?

I was hoping the printed values ​​would be "200!" and "404!" in Python3.4. But I got the results "200!" and further!".

I made a strange face - and tried it again in C. The results in C are not the same as in Python3. Why?

Python3.4 Code

def chk(s): 
    if s is 200:
        print('200!')
    elif s is 404:
        print('404!')
    else:
        print('else!')

chk(200)
chk(404)

      

Python3.4 code result

200!
else!

      

C code

#include <stdio.h>

void chk(int s) {
    if (s == 200)
        printf("200!");
    else if (s == 404)
        printf("404!");
    else
        printf("else!");
}

int main(void) {
    chk(200);
    chk(404);
    return 0;
}

      

C code result

200!404!

      

+3


source to share


2 answers


is

does not mean "equal" as such. In fact, this means that "occupies the same place in memory". Also, usage is

for numbers has strange behavior, depending on the version of python used. (And by that I mean Cpython vs Jpython vs pypy vs ....) So don't use it, use ==

for numbers.

def chk(s): 
    if s == 200:
        print('200!')
    elif s == 404:
        print('404!')
    else:
        print('else!')

chk(200)
chk(404)

      

(If you want more details on why 200 is 200

it gives True

, but 404 is 404

gives False

: basically, the numbers from -5

to 256

are cached in CPython. Each of them gets its own little memory slot, and if assigned to a variable, CPython just sorts the points that change by relative to a predefined memory slot. This does not apply to numbers outside this range. If necessary, CPython will go to find an empty memory slot, put a number there and hover over it. If you assign 404 to two separate variables, you have two separate integers the 404s that are posted in memory.)



More details:

When to use is

, when to use ==

.

CPython, is

and why you should never use it with numbers

+7


source


is

is basically compared for object identity. Please note that Python names

is just references to actual objects. So the C equivalent would be basically:

int k = 200, *i;
const int c = 200;

i = &k;

if ( i == &c )
    // fails, but *i == c is true
    .... 

      

Thus, you should not use is

to compare values ​​for equality, but only for identification. The most important use case is:

if val is None:
    ...

      



Since there is exactly one None

object.

if val == None:
    ...

      

OTOH will obey the rules of coercion, thus it will be true for other other cases as well.

Read here (find paragraph about is

) and footnote for details.

+1


source







All Articles