简体   繁体   中英

Python Caesar cipher with two keys

I want to write a caesar cipher with two keys; one for vowels and another for consonants.

I have words with only capital letters. I've written some code, but I know this is wrong. I want to follow that way. Can someone help me:

def ceasar(word, key1, key2): 
    c = "" 
    for i in range(len(word)): 
        zn = word[i]
        for x in zn:
                        if x=="A" or x=="E" or x=="I" or x=="O" or x=="U":
                                c += chr((ord(zn) + key1-65) % 26 + 65)                               
                else:
                                c += chr((ord(zn) + key2-65) % 26 + 65)


    return c

Just catering for upper case letters and no other characters, you can get it working by simplifying it a little to:

def caesar(word, key1, key2):
    c = ""
    for x in word:
        if x in "AEIOU":
            c += chr((ord(x) + key1 - 65) % 26 + 65)
        else:
            c += chr((ord(x) + key2 - 65) % 26 + 65)
    return c

You had two loops, but that's unnecessary as in your code, zn is only a single character anyway, so doesn't need a second loop.

I've simplified your vowel check, as you can check if a character appears in a string much more simply than using multiple or conditions.

It's also much more common in Python to loop over an iterator by value, rather than by looping over an index and then using that index value to access the iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM