1

I want to encrypt some letters by changing each letter with the character in echaracters which has the same index as the letter in characters. So, I tried to use zip() to iterate over the two lists. Firstly I iterated over userInput and the within the same loop, I iterated over key (which is zip(characters, echaracters)) Then I check if i is equal to a and if the condition is True i add b to cipher.

userInput = input("Enter: ")

characters = ["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"]

echaracters = ["@", "$", "(", "]", "=", ")", "&", "#", "!", "%", "~", "[", "/", ";", "*", "}", "9", "?", "5", "1", "_", ">", "<<", "+", ",", "-"]

key = zip(characters, echaracters)

cipher = ""

for i in userInput:
    for a, b in key:
        if i == a:
            cipher += b

print(cipher)

OUTPUT

Enter: ABC
@

I cannot figure out why it returns only the first symbol.
DESIRED OUTPUT

Enter: ABC
@$(

What am I doing wrong?

Emanuele
  • 174
  • 13

3 Answers3

2

Your key becomes empty after the first loop pass

You can try this:

key=list(zip(characters, echaracters))
for i in userInput:
    for a, b in key:        
        if i == a:            
            cipher += b
Arseniy
  • 680
  • 5
  • 10
2

The reason is because 'key', which is a zip-type, loses its value after the first iteration because zip-type is an iterator. Here is a similar question. Your code is a bit complicated. There is easier way to accomplish your task.

userInput = input("Enter: ")
characters = ["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"]
echaracters = ["@", "$", "(", "]", "=", ")", "&", "#", "!", "%", "~", "[", "/", ";", "*", "}", "9", "?", "5", "1", "_", ">", "<<", "+", ",", "-"]

cipher = ""
for i in userInput:
  cipher += echaracters[characters.index(i)]
print(cipher)
Aven Desta
  • 2,114
  • 12
  • 27
1
SYBMOLS = {
    "A": "@",
    "B": "$",
    "C": "(",
    "D": "]",
    "E": "=",
    "F": ")",
    "G": "&",
    "H": "#",
    "I": "!",
    "J": "%",
    "K": "~",
    "L": "[",
    "M": "/",
    "N": ";",
    "O": "*",
    "P": "}",
    "Q": "9",
    "R": "?",
    "S": "5",
    "T": "1",
    "U": "_",
    "V": ">",
    "W": "<<",
    "X": "+",
    "Y": ",",
    "Z": "-",
}

userInput = input("Enter: ")

for symbol in userInput:
    print(SYBMOLS[symbol], end="")


Also, if you want just lists and not a dictionary, instead of:

characters = ["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"]

You can use

from string import ascii_uppercase

print(ascii_uppercase) # example zip(ascii_uppercase, echaracters)

# ABCDEFGHIJKLMNOPQRSTUVWXYZ
GolangMan
  • 21
  • 4