I'm struggling to iterate past the first character of a string in a for loop when ord() is being used

108 Views Asked by At

I am trying to make a Ceasar Cipher. Struggling to get the ord() then shift it and then chr() for the encryption. I can get the first character in 'abc' and get an output of 'b' but not the whole string 'bcd'.

I feel it has to do with the return or not meeting the condition of going through the whole range, but I don't know how to troubleshoot. Any help would be fantastic.

Thanks in advance.

def cCipher(text,shift):
    #First identify whether text is a string or note.
    if type(text) != str:
        return "The input is not a string"

    #Get the ord() for each letter in string and shift
    else:
        for i in range(len(text)):
            code = chr(ord(text[i])+shift)
            return code


#This will be my test functions
print(cCipher('abc', 1))
1

There are 1 best solutions below

4
Kapocsi On

You are terminating the function by calling return code.

Try this instead:

def cCipher(text,shift):
    #First identify whether text is a string or note.
    if type(text) != str:
        return "The input is not a string"

    #Get the ord() for each letter in string and shift
    else:
        code = ""
        for i in range(len(text)):
            code += chr(ord(text[i])+shift)
        return code


#This will be my test functions
print(cCipher('abc', 1))

Please note that there are other deficiencies in this code. The revised version I posted above fixes the issue you are experiencing but does not address any other issues.