M. Dodd
M. Dodd

Reputation: 5

How do I make this caesar cipher work with capital letters using an IF statement in the FOR loop?

This is my caesar cipher so far- it works with spaces but it won't work with capitals. Can you please help me put in an IF statement to get it to work? I've tried:

elif letter==letter.upper():
    finalphrase=alphabet[(alphabet.index(letter)+offset)%26].upper()

but it still doesn't work...

#Caesar Cipher - Encrypts/Decrypts the user's input

#Asking the user if they want to encrypt or decrypt a word/phrase
EorD = input("Please input either 'e' (for encrypt) or 'd' (for decrypt): ")

#IF Statement to decide whether the offset gets saved as a positive or a            negative integer
if EorD.lower() == 'e':
    offset = int(input("Please input your chosen offset: "))
elif EorD.lower() == 'd':
    offset = -int(input("Please input your chosen offset: "))
else:
    print("Error")

#Asking the user for their phrase
phrase = input("Please input a word/phrase: ")

#alphabet stored in a list
alphabet=  ["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"]

#A FOR loop - to loop through the individual letters in the phrase 
for letter in phrase:
    if letter in alphabet:
        finalPhrase = alphabet[(alphabet.index(letter)+offset)%26]
    else:
        finalPhrase = letter
    print(finalPhrase, end="")

Upvotes: 0

Views: 854

Answers (3)

user4484761
user4484761

Reputation:

Rémi was able to show you what you had wrong in your index search. I'd also like to add that the if statement in the for loop could be:

if letter.lower() in alphabet:

This will return the cipher as a lowercase, but from here I think you should be able to figure out the rest if you want to return an uppercase solution.

Upvotes: 1

M. Dodd
M. Dodd

Reputation: 5

I did it!!!

for i in word:
    if i in alphabet:
        newword = alphabet[(alphabet.index(i)+offset)%26]
    elif i==i.upper():
        newword = alphabet[(alphabet.index(i.lower())+offset)%26].upper()
    else:
        newword = i
    print(newword, end="")

Upvotes: 0

Rémi
Rémi

Reputation: 3744

Replace

 alphabet.index(letter)

by

 alphabet.index(letter.lower())

Upvotes: 1

Related Questions