Search code examples
pythonpython-3.xloopsascii

Cryptography with ASCII in python 3


I am trying to make a cryptography program.

When I run this program and insert for example abc with shift 2 it will return cde which is good. But I tried to insert xyz aswell with shift 3 and instead of shifting correctly abc it returns aaa. This also happens if I use shift 2 then it returns zaa.

How can I adjust my program to correctly start from the beginning when the alphabet is done with the ASCII tabel?

shift = int(input("Please insert a number you want to shift the characters with: "))

end = ""

for x in alf:
    ascii = ord(x)

if ascii >= 97 and ascii <= 122:
    res = ascii + shift
    if res > 122:
        res = 0 + 97
        min = res + shift
    end = end + chr(min)

print (end)                                

Solution

  • It is because your logic expression is wrong. Here is an example that will allow any positive integer as right shift, beginning again at a again. And it can be very much optimized (hint: use modulo operator), but this is with minor changes to your code and numerics written out loud.

    for x in alf:
      ascii = ord(x)
    
      if ascii >= 97 and ascii <= 122:
        res = ascii + shift
        while res > 122:
          res = res - (122 - 97) - 1
        end = end + chr(res)