Scientific Computing with Python (BETA) - step 72

text = 'Hello Zaira'
custom_key = 'python'

def vigenere(message, key, direction):
    key_index = 0
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    encrypted_text = ''

    for char in message.lower():
    
        # Append space to the message
        if char == ' ':
            encrypted_text += char
        else:        
            # Find the right key character to encode
            key_char = key[key_index % len(key)]
            key_index += 1

            # Define the offset and the encrypted letter
            offset = alphabet.index(key_char)
            index = alphabet.find(char)
            new_index = (index + offset*direction) % len(alphabet)
            encrypted_text += alphabet[new_index]
    
    return encrypted_text
encryption = vigenere(text, custom_key, 1)
print(encryption)

Can someone explain me about:

  • why using 1 as a call passing?
  • what difference that direction argument makes, before and after adding it to the code?
  • why the output doesn’t change after modifications? (output: wcesc mpgkh)

Thanks.

1 Like

I do not know Python - not at all, actually - but it seems to me, knowing a tiny bit about the general idea of encryption, that the answers to your questions are something like this:

direction = 1 indicates encryption, while direction = -1 would indicate decryption. Why and how, I am not confident, but it seems to me that it could be any number, not just one, as long as both are equal in absolute value. 1 shifts the character index up by a certain offset by multiplying the offset by 1, and -1 shifts the index back down by subtracting that offset value to decrypt. But if they’re 2 and -2, for example, they would also shift reciprocally up and down, from encryption to decryption, I think. I don’t know, I’m just guessing. I suppose they kept it at 1 and -1 for simplicity.

It looks like, as I explained (terribly!) above, it shifts the index by the offset value multiplied by direction, and thus will be added if direction is positive and subtracted if direction is negative. That is all I could see - I apologize if I’m being redundant!

Edit: my apologies, upon a bit more research it looks like the answer is simpler than I thought:

You’re printing the encrypted version. So the fact that the output is strange (wcesc mpgkh) is actually a good thing. That’s the encrypted version of ‘Hello Zaira’.

I hope that helped at least a tiny bit. Once again, I apologize!

Happy encrypting,

Nicolas

1 Like