Please tell me why this code gives this error? <String>: 2: SyntaxWarning: "is" with a literal. Did you mean "=="? | SoloLearn: Learn to code for FREE!

0

Please tell me why this code gives this error? <String>: 2: SyntaxWarning: "is" with a literal. Did you mean "=="?

Code: n=3 if n is 2: print ('y') else: print ('n')

3/3/2021 11:48:32 AM

Masoud Amiri Batmanghlnj

3 Answers

New Answer

+2

First Of All its a warning not an error, the 'is' keyword is to used to check if two variables refer to the same object or not and it actually compares their location not the variable, You Will Get False Even If They Holds The Same Value. eg- class A: def __init__(self, num): self.num=num n = A(3) m = A(2) print(n is m) #False print(n.num is m.num) #False q = A(3) print(q is n) #False print(q.num is n.num) #True more info at https://www.w3schools.com/python/ref_keyword_is.asp#:~:text=The%20is%20keyword%20is%20used,if%20two%20variables%20are%20equal.

+3

There’s a subtle difference between the Python identity operator (is) and the equality operator (==). source: https://realpython.com/courses/python-is-identity-vs-equality/ in your case "==" would be the correct operator

+1

its telling you not to use 'is' like that. When comparing values, use == (equal to). ... snippet ... if n == 2: ... ...