1

can somebody please explain me the difference between if i use "if not ... in" or "!=" in my code

alphabet = "abcdefghijklmnopqrstuvwxyz"
punctuation = ".,?'! "
message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!"
translated_message = ""
for letter in message:
    if letter != punctuation:
        letter_value = alphabet.find(letter)
        translated_message += alphabet[(letter_value + 10) % 26]
    else:
        translated_message += letter
print(translated_message)

output:

heyjtherejjthisjisjanjexamplejofjajcaesarjcipherjjwerejyoujablejtojdecodejitjjijhopejsojjsendjmejajmessagejbackjwithjthejsamejoffsetj

if i use "If not letter in message"

i get this as output:

hey there! this is an example of a caesar cipher. were you able to decode it? i hope so! send me a message back with the same offset!
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
EvaIgoria
  • 35
  • 3
  • 2
    `letter != punctuation` if `letter` and `punctuation` aren't identical — which is always the case in your code. `letter not in punctuation` if `letter` is not _contained_ in `punctuation`. – L3viathan Nov 08 '21 at 15:40
  • 1
    Good explanation here: [!= vs not in](https://stackoverflow.com/questions/2209755/python-operation-vs-is-not) – Shaddo Nov 08 '21 at 15:43
  • @Shaddo That question is asking about an equality check vs. an identity check. OP's question is asking about an equality check vs. a membership check. – Axe319 Nov 08 '21 at 15:56
  • Btw, rather than use `alphabet.find`, you should create a dictionary of letters to numbers – OneCricketeer Nov 08 '21 at 16:01

3 Answers3

3

NOT IN search if the target element is another element : "b" in "abc" should return True

!= or == compares the elements of the two sides of the equality and not their belonging : "b" == "abc" should return False

for letter in message:
    translated_message += letter if letter in punctuation else alphabet[(alphabet.find(letter) + 10) % 26]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Alexis Leloup
  • 250
  • 1
  • 8
0

the != means (Not equal to) and if not means (Not equal to) also!

there is no difference between them

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
sMx_7d
  • 37
  • 6
0

The in operator is used to determine whether or not a string is a substring of another string. (Same goes to not in) For example,

if "tom" in "tomato":  
if "cat" in "catalogue":  
if "2" in "234":  
if "4" not in "890":  # or ... if not ("4" in "890")

And so on.
Similarly, != operator is used to compare the values on either sides of them and decide the relation among them. ( a != b ) means If values of two operands are not equal, then condition becomes true. So, it's not good to use this operator to check a particular string is included inside another string.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Python learner
  • 1,159
  • 1
  • 8
  • 20