Search code examples
python-3.xnested-loops

Python cypher and nested loops


I'm very new to python and I am having trouble with a cypher problem. I need to display 3 columns relating to two input statements. the user inputs are 'message' and 'keytext'. The first column simply spits out the 'message' one letter at a time. The second column displays a numeric value for the 'keytext' input. The third column displays the new text which is created by moving the letters in 'message' by the corresponding value indicated by 'keytext' (sorry this is a bit hard to describe)

Message? HELLO
Keytext? AAAA
H 0 H
E 0 E
L 0 L
L 0 L
O 0 O

Message? HELLO
Keytext? ABBCD
H 0 H
E 1 F
L 1 M
L 2 N
O 3 R

Now I know how to do a simple cypher but its getting all three columns to display and cooperate at once that I just can't figure out and can't seem to find an answer anywhere. (Or possibly I just don't know the right thing to ask)

This is my code at the moment, and in this variation I can't seem to get the middle column to iterate properly.

keytext = str(input("Keytext? ").upper())
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for i in message:
    place = alphabet.find(i)
    for j in keytext:
        place2 = alphabet.find(j)
        newplace = (place + place2)% 26
        code = alphabet[newplace]
    print(i,place2,code)

if message = hello and keytext = abcde, then the expected output would be

H 0 H
E 1 F
L 2 N
L 3 O
O 4 S

However it is currently:

H 4 L
E 4 I
L 4 P
L 4 P
O 4 S

So its just figuring out how to fit column 2 in the loops properly... Does anyone have any suggestions for how I can go about fixing this? Any help would be really apprectiated.

Thanks!


Solution

  • You did figure out how to do it- Apart from a small deviation. In the inner for loop, j iterates over the keytext and the code is overwritten. Hence the deviation from the expected output. All you have to do is remove the inner for loop.

    message = str(input("Message? ")).upper()
    keytext = str(input("Keytext? ")).upper()
    
    # Length of keytext and message should be same.
    assert len(message) == len(keytext)
    
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i in range(len(message)):
        place = alphabet.find(message[i])
        place2 = alphabet.find(keytext[i])
        newplace = (place + place2) % len(alphabet)
        code = alphabet[newplace]
        print(message[i], place2, code)
    

    Output:

    Message? hello
    Keytext? abcde
    H 0 H
    E 1 F
    L 2 N
    L 3 O
    O 4 S