Home > database >  Both codes work(caesar cipher): but one code rearranges the output
Both codes work(caesar cipher): but one code rearranges the output

Time:11-23

Beginner python programmer here. Before I knew about using .index(), i used a work around. Whilst it did work something peculiar happened. The output string was re-arranged and i don't know why.

Here is my code:

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']

text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))


#input for text = "code" integer for shift = 5

#First attempt


for index, price in enumerate(alphabet):
    new_index = shift   index
    for loop in text:
        if loop == price:
            print(alphabet[new_index])
#Second attempt using .index 

for letter in text:
    position = alphabet.index(letter)
    new_index = position   shift
    print(alphabet[new_index])

Here are the outputs

output for first code = hijt

output for second code = htij

CodePudding user response:

Your first code prints the word with the letters rearranged in alphabetical order (before using the cipher). You go through the alphabet in your enumerate, a-z, and you look for each letter in your word. For example, if your word was 'ba', with a shift of one, it should output 'cb' - but it outputs 'bc'. It is because your loop looks for 'a's and prints the converted values out before doing so for 'b's.

Your second is correct.

Note: I have no idea why your sample output is on a single line - print generally adds a newline, so each letter would have been on a separate line. Also, you should realize that your code doesn't work when the new letter goes past 'z' - it has an index out of range error.

  • Related