Unable to get desired output for Caesar Cypher

122 Views Asked by At

I am trying to create a function for a Caesar Cypher that converts any string to its respective unicode using the ord() function and then shifts the unicode by two steps.

For example, the unicode for the string 'a' is the integer 97.

print(ord('a'))

After that this shifted unicode is converted back to its respective character to produce a piece of code that is inscrutable.

. Traceback (most recent call last): File "main.py", line 11, in Ccypher(msg) File "main.py", line 9, in Ccypher a = a + str(chr(lst[i])) UnboundLocalError: local variable 'a' referenced before assignment**

I tried to convert a to a global variable by adding global a in the body of the function but then I got no output, just blank.

The code I wrote is as follows:

lst = list()
a = ''
msg = "Meet me at the Ritz Carlton at 9 o'clock, don't be late!" #message to encrypt

def Ccypher(string, shift = 2):
    for i in range(len(msg)):
        lst.append(ord(msg[i]) + shift)
        a = a + str(chr(lst[i]))
    return a
Ccypher(msg)
3

There are 3 best solutions below

0
Expurple On

On my machine, with global a added, the return value of Ccypher(msg) is not blank: 'Oggv"og"cv"vjg"Tkv|"Ectnvqp"cv";"q)enqem."fqp)v"dg"ncvg#'. You've probably just forgot to print it

0
vlados155 On

The problem can be easily solved without global variables. You need to declare variables in the body of the function before the loop, you also need not just call the function, but print its result:

msg = "Meet me at the Ritz Carlton at 9 o'clock, don't be late!" #message to encrypt

def Ccypher(string, shift = 2):
    a = ''
    lst = list()
    for i in range(len(msg)):
        lst.append(ord(msg[i]) + shift)
        a = a + str(chr(lst[i]))
    return a
print(Ccypher(msg))

Please note, your "cipher" is not the real Caesar cipher. Caesar's cipher should encode only letters (in this case, for letters, and not for other symbols), excluding punctuation marks and numbers

0
Malo On

As said before, all variable souhld be declared inside the function, no need of global variables here (it is often bad practice).

And just print the final result returnd by your function, otherwise it is computed but lost:

def Ccypher(string, shift = 2):
    lst = list()
    a = ''
    for i in range(len(msg)):
        lst.append(ord(msg[i]) + shift)
        a = a + str(chr(lst[i]))
    return a

msg = "Meet me at the Ritz Carlton at 9 o'clock, don't be late!" #message to encrypt

print(Ccypher(msg))

PS original Caesar Cypher was a shift by 3 letters