Search code examples
pythonrot13

Why is my python code only ciphering a message with capitals?


I am trying to make a script that rotates each letter of a message by 13 letters, creating a simple cipher. I have my cipher rotating the letters properly, the problem I have is that it only ciphers it to capital letters.

For example, for I input "Hello ! World", it should return "Uryyb ! Jbeyq" but its returning "URYYB ! JBEYQ"

uppercase = ['A','B','C','D', 'E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ciphered = ""
for i in message:
    if i.isalpha():
        if i in uppercase: # checks if letter (i) is an upper case and treats it as such
            letter = uppercase.index(i)
            rotated = uppercase[(letter + 13) % 26] # used to loop through alphabet
            ciphered = ciphered + rotated
        else:
            letter = lowercase.index(i) 
            rotated = uppercase[(letter + 13) % 26] # used to loop through alphabet
            ciphered = ciphered + rotated
    else:
        ciphered = ciphered + i
return ciphered

Solution

  • Small mistake, in the else condition, you are using the uppercase list. Change it lowercase:

    uppercase = ['A','B','C','D', 'E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    ciphered = ""
    for i in message:
        if i.isalpha():
            if i in uppercase: # checks if letter (i) is an upper case and treats it as such
                letter = uppercase.index(i)
                rotated = uppercase[(letter + 13) % 26] # used to loop through alphabet
                ciphered = ciphered + rotated
            else:
                letter = lowercase.index(i) 
                rotated = lowercase[(letter + 13) % 26] # used to loop through alphabet
                ciphered = ciphered + rotated
        else:
            ciphered = ciphered + i
    return ciphered