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


i hoped values printed "200!" , "404!" in python3.4. got results "200!" , "else!".

i made strange face — , tried again in c. results in c not same in python3. why?

python3.4 code

def chk(s):      if s 200:         print('200!')     elif s 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! 

is doesn't mean "equal", per se. means "occupies same location in memory." additionally, using is on numbers has odd behavior, depending on version of python you're using. (and this, mean cpython vs jpython vs pypy vs....) don't use it, use == numbers.

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

(if want more details why 200 200 yields true 404 404 yields false: basically, numbers -5 256 cached in cpython. each little slot of memory, , if they're assigned variable, cpython sort of points variable towards preassigned slot of memory. not case numbers outside range. if needed, cpython go find empty slot of memory, put number there, , point variable @ it. if assign 404 2 separate variables, have 2 separate integers of 404 hanging out in memory.)

for more:

when use is, when use ==.

cpython, is, , why should never use numbers


Comments