Ceasar coding returns wrong characters

71 views Asked by At

enter image description here the issue I think is within the if statement('s) but I can't find the problem after tweaking for a bit.

txt = "xofob qyxxk qsfo iye ez, xofob qyxxk vod iye nygx"

def letterschuiven(cha, vsg):

      for let in cha: 
          let = let.lower()

          if let.isalpha():
               numberlet = ord(let) + vsg
               if numberlet < 97:
                  modlet=  numberlet % 26
                  answer = modlet + 97
               else:
                    answer=numberlet
               realans = chr(answer)
               print(realans, end = "")
          else:
               print(let, end = "")
letterschuiven(txt, -10)

should return "never gonna give you up, never gonna let you down", now returns: "neoek gonna gioe ron np, neoek gonna lem ron dopn"

(here the explanation of the def) I am trying to decode txt using CHA as the string, and vsg as the amount the characters should be moved (-10 here)

gives neoek gonna gioe ron np, neoek gonna lem ron dopn should return never gonna give you up, never gonna let you down

I tweaked most values a bit but that just made it all worse

I think the answer is pretty simple, but please try to keep it to a beginner level (school project ;))

1

There are 1 answers

0
oszkar On

You have to change the line

modlet =  numberlet % 26

to

modlet =  (numberlet - 97) % 26

as the 'a' character has the decimal code 97, so you want to set that as 0 before getting mod 26. This way numberlet - 97 tells you how steps you have to take after 'z', hence (numberlet - 97) % 26 tells how many steps you have to take from 'a'.

Btw this way you even don't need the

               if numberlet < 97:
                  modlet =  numberlet % 26
                  answer = modlet + 97
               else:
                    answer  =numberlet

part, simply use

answer  =  (ord(let) + vsg- 97) % 26 + 97

instead.