Search code examples
pythonloopsencryptioncaesar-cipher

Caesar Cipher python program looping issue


Okay, so I have gotten this far with a Caesar cipher program in python and cannot see any reason why this doesn't work, but it doesn't... it outputs the new word as 'a' 'a' 'a' (for however many letters were in the word). My guess is its some kind of loop that results in each letter being changed into 'a' but I just can't figure it out. Can anybody out there help me? Thanks.

My code:

word = input("please enter the word you wish to encrypt: ")
seperated = list(word)
length = len(word)
alphabet1 = ["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"]
alphabet2 = ["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"]
length2 = len(alphabet1)
length3 = len(alphabet2)


for eachposition in range(length):
    for letter in range(length2):
            if seperated[eachposition] == alphabet1[letter]:
                    seperated.pop(eachposition)
                    seperated.insert(eachposition, alphabet2[letter])

print(seperated)

Solution

  • I added some print calls to your code and got lots of false positives where seperated[eachposition] == alphabet1[letter] was evaluating as True when it shouldn't. From that I realised the problem pretty quickly.

    You never use break from your loop, so here's what's happening:

    • I enter "word"
    • The loop runs until it finds that the first letter is the same as the letter 'w' in alphabet
    • The first letter of separated is set as 'x', due to how your cipher works
    • The loop keeps running, now testing if the first letter is 'x'

    Since your cipher just advances each letter on one, this loop will always run until it reaches the last letter in your list, 'a'.

    The simple fix is to use break. It will end a for loop prematurely. Meaning that when you have replaced a letter, you want to break out of that inner loop and move onto the next character.

    for eachposition in range(length):
        for letter in range(length2):
            if seperated[eachposition] == alphabet1[letter]:
                seperated.pop(eachposition)
                seperated.insert(eachposition, alphabet2[letter])
                break