简体   繁体   中英

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="")

Replace

 alphabet.index(letter)

by

 alphabet.index(letter.lower())

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.

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="")

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