pythoncaesar-cipher

Python Caesar Cipher


I need to create a code for Caesar Cipher. I need to use a for loop to examine every character of text, find shifted character using ALPHABET, key, and String functions, and add this to the end of "encipheredTextSoFar". Need help, not finished but I'm stuck.

EDIT:

I finally got it and this is my final code:

def circularShift(text, key):
    text = text.upper()
    cipher = ""
    for letter in text:
        shifted = ord(letter) + key
        if shifted < 65:
            shifted += 26
        if shifted > 90:
            shifted -= 26
        cipher += chr(shifted)
    return cipher

print (circularShift("MOLLOY", 3))
print (circularShift("PROORB", -3))

Solution

  • Python source code:

    # setting status default value to 'y'
    status = 'y'
    
    # started a while loop until status will change from 'y' to 'n'
    while status == 'y':
        # requesting which word to cipher.
        word = str(raw_input("Word: "))
        # how many position to shift each letter
        shift = int(input("Shift: "))
        # added new line to have pretty output
        print
    
        # declaring cipher variable to be of type list
        cipher = list()
        # iterating trough each character in word
        for item in word:
            # translanting each characher in word to new character
            # and appending it to cipher list
            cipher.append(chr(ord(item)+shift))
    
        # printing word
        print word
        # printing ciphered word
        print ''.join(cipher)
    
        print
        # do We need to cipher another word? yes or no?
        status = raw_input("Repeat? [y|n]: ")
        print    
    

    Output:

    >>> 
    Word: HelLo
    Shift: 1
    
    HelLo
    IfmMp
    
    Repeat? [y|n]: y
    
    Word: AbCdEF
    Shift: 2
    
    AbCdEF
    CdEfGH
    
    Repeat? [y|n]: y
    
    Word: abc
    Shift: -1
    
    abc
    `ab
    
    Repeat? [y|n]: y
    
    Word: 456GHh
    Shift: -2
    
    456GHh
    234EFf
    
    Repeat? [y|n]: n
    
    >>>