Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.append() is replacing element, instead of adding new element to the list

I am trying to create a cipher program, here text entered by the user will be shifted to the letters according to the shift variable. so here I have created an empty list called encrypt and trying to append characters after shifting them to the list.
But it’s just replacing the letter in the list instead of adding a new item in the list.

Here’s the 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']

#direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

#TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
def encrypt(text,shift):
    for letter in text:
        encrypted = []
        position = alphabet.index(letter) + shift
        encrypted.append(alphabet[position])
    print(''.join(encrypted))
    
encrypt(text,shift)

Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are basically overwriting your list everytime in the loop. here

def encrypt(text,shift):
    for letter in text:
        encrypted = [] #This runs every iteration, so there will be only 1 at end
        position = alphabet.index(letter) + shift
        encrypted.append(alphabet[position])
    print(''.join(encrypted))

Move it out of the loop, things must be fine.

def encrypt(text,shift):
    encrypted = []
    for letter in text:

        position = alphabet.index(letter) + shift
        encrypted.append(alphabet[position])
    print(''.join(encrypted))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading