2

Why is my encrypt function only returning the first translated letter? (I've cut out the decrypt and brute force -function). The issue is probably a small one but I'm new to this and I've been staring at it too long for anything to pop into my head.

import string

def encrypt(message,key):
    cryptotext=""
    for character in message:
        if character in string.uppercase:
            old_ascii=ord(character)
            new_ascii=(old_ascii+key-65)%26+65
            new_char=chr(new_ascii)
            cryptotext+=new_char
            return cryptotext

        elif character in string.lowercase:
            old_ascii=ord(character)
            new_ascii=(old_ascii+key-97)%26+97
            new_char=chr(new_ascii)
            cryptotext += new_char
            return cryptotext

        else:
            return character
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) is you friend here, you wouldn’t even have to ask a question if you'll follow an advice given there. – Łukasz Rogalski May 10 '15 at 16:55

2 Answers2

1

The return statement breaks from the current loop, which means that the encrypt function should wait until after the loop to return: Also note that you should append the character if it isn't upper or lower case, or it will just return the first wrong letter.
So encrypt(message,key) should look like:

def encrypt(message,key):
    cryptotext=""
    for character in message:
        if character in string.uppercase:
            old_ascii=ord(character)
            new_ascii=(old_ascii+key-65)%26+65
            new_char=chr(new_ascii)
            cryptotext+=new_char


        elif character in string.lowercase:
            old_ascii=ord(character)
            new_ascii=(old_ascii+key-97)%26+97
            new_char=chr(new_ascii)
            cryptotext += new_char


        else:
            #Also, append character to cryptotext instead of returning it
            cryptotext+= character
    return cryptotext
IronManMark20
  • 1,298
  • 12
  • 28
0

You put the return statements inside the loop. That means that after the first iteration you exit from the function and you have only a single character as a result.

Your code should look something like this:

cryptotext = ""
for character in message:
    # ...
    # do the encryption, without returning
    # ...
return cryptotext # after the loop has finished
mkrieger1
  • 19,194
  • 5
  • 54
  • 65