Python Forum

Full Version: Monoalphabetic cipher
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!
I wrote this code:
keys={'a':'z','b':'y','c':'x','d':'w','e':'v','f':'u','g':'t','h':'s','i':'r','j':'q','k':'p','l':'o','m':'n'}
reverse_keys={}
for key,value in keys.items():
    reverse_keys[value]=key
def encrypt(text):
    text=str(text)
    encrypting=[]
    for l in text:
        encrypting.append(keys.get(l,l))
    print(''.join(encrypting))
def decipher(text):
    text=str(text)
    decrypted=[]
    for l in text:
        decrypted.append(reverse_keys.get(l,l))
    print(''.join(decrypted))
print(encrypt("hej"))
print(decipher("svq"))
But now I want to create a function encrypt(text,keys) for example encrypt(hej,"zyxwvutsrqponmlkjihgfedcba"). I want the user to define the key himself.
I would make keys a parameter to decipher, with a default (as a string like in your desired example) equivalent to what the global variable is now. Convert that to a dictionary like keys is now, and use that for encryption. Of course, first you need to fix the fact that your keys only cover half the dictionary, so only half the letters get encrypted.