0

Python: How to encrypt a string of character length n by an 8 digit key.

My Code so far is below - however it will only encrypt the length of the string up to the 8th digit in key (or key length). I need to reset the key when it comes to it's end and continue for the rest of the string. Really stuck on this one. Any guidance or help would be really appreciated.

def code_char(c,key):
    c = ord(c)
    if c >= 65 and c <= 90:
        c = c + key
        if c <= 90:
            return chr(c)              
        while c > 90:
            c = c - 26
            return chr(c)
    elif c >= 97 and c <= 122:
        c = c + key
        if c <= 122:
            return chr(c)                   
        while c > 122:
            c = c - 26
            return chr(c)

def code_block(word, key):
    newWord = ""
    for char, num in zip(word, key):
        newWord = newWord + code_char(char, int(num))        
        return newWord 

print(code_block('abcdefghijklmn','111111111'))

Thanks for help - should have stated I'm not allowed to use any built in functions for this.

Harry.A
  • 1
  • 1
  • Using `while` rather than `else` is an odd choice. Also, even using `if` there rather than using modular arithmetic makes the code needlessly long. – John Coleman Mar 11 '17 at 19:14
  • Thanks for heads up. Will that be an issue later on or just unnecessary? – Harry.A Mar 11 '17 at 19:21
  • Using a while when you really mean else is convoluted, and sooner or later convoluted code is an issue. Also, you *are* using modular arithmetic here, so you might as well make that explicit by using %. – John Coleman Mar 11 '17 at 19:28

1 Answers1

0

You can make code_block match the key length to the length of the word before starting the loop. Using a very good solution from Repeat string to certain length

you could write it as:

def code_block(word, key):
    newWord = ""
    work_key = (key * ((len(word)/len(key))+1))[:len(word)]
    for char, num in zip(word, work_key):
        newWord = newWord + code_char(char, int(num))        
    return newWord

See it in action here: https://eval.in/752994

Community
  • 1
  • 1
sal
  • 3,515
  • 1
  • 10
  • 21