-3

I have tested a simple loop which doesn't work... If the "selected_cate" input is in the dictionnary values CATE.values(), it is supposed to print a messsage saying that it worked and add it in the global dataframe (column categ) data.categ[index]. When I give an input which is clearly in the dictionnary, it still doesn't work while the line tried alone work for the true statement !! (see the picture).

(in the test line "LIBELLE" replaces "lib" in the code, it is only a simple string)

for i in data.index:
pd.options.mode.chained_assignment = None  # default='warn'
lib=data.libelle[i]
if data.categ[i]=='AUTRE':

    while True:
        selected_cate=input("___# " + lib + " #___ "+" va dans quelle catégorie ? ").upper()
        if selected_cate in CATES.values() is True: 
            print("Dictionnary CATES contains selected_case")
            data.categ[i]= selected_cate
            break
        else:
            print("erreur : catégorie non reconnue")

Thanks for helpingenter image description here

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Xomuama
  • 153
  • 7
  • 2
    Not clear what you want to achieve and what is your problem. – log0 Apr 21 '20 at 14:08
  • Try to make your question title clear enough that someone can tell if they have the same problem just by reading it. Any number of completely unrelated problems could cause the wrong side of an `if` to be taken, so this title isn't really useful. – Charles Duffy Apr 21 '20 at 14:17
  • Also, **don't** post screenshots of code -- instead, transcripts of code or REPL sessions should be included as text. See [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/a/285557/14122) on [meta]. – Charles Duffy Apr 21 '20 at 14:19
  • Ok, sorry for being unclear, i'll make an effort next time. I have my answer – Xomuama Apr 21 '20 at 14:24

2 Answers2

1

It probably comes from the parentheses :

1 == 1 is True 
# returns False beause equivalent with 1 == (1 is True)

(1 == 1) is True 
# returns True

Therefore you should use

if (selected_cate in CATES.values()) is True:

that actually boils down to

if selected_cate in CATES.values():
Kokli
  • 155
  • 7
0

Note that

 selected_cate in CATES.values() is True

is not the same as

selected_cate in CATES.values()

In the first case the is operator is chained to the in operator so the line is equivalent to

selected_cate in CATES.values() and CATES.values() is True

which is false.

There are many subtleties with the is operator that might depend on your Python implementation/version. For instance small integers are often cached so two 1s might be the same object in memory but not two 500000s...

In [32]: 1+1 is 2
Out[32]: True
In [33]: 5000+1 is 5001
Out[33]: False

The general recommendation is to avoid using is unless you really want to know if it is the same object in memory.

log0
  • 10,489
  • 4
  • 28
  • 62