I am trying to complete the vigenere cipher assignment. I am encountering an error that I cannot figure out with these two lines:
k = key[i] % m
cipher_text = cipher_text + chr((ord(letter) - 97 + k) % 26 + 97)
The bottom line above will not process due to the “k” variable definition above it. I cannot figure out how to return the index value of my key. Currently running this code results in this error on the first line: “TypeError: not all arguments converted during string formatting”. I have tried using the int(), float(), and index() functions to no avail. Can anyone tell me what I am missing?
It should represent an integer, yes; specifically it should be the integer value of the key’s index within the current loop of the function. But for some reason it is not being interpreted as one when I run my code and I’m not sure why.
The key is given as a string parameter in a function, and it should be getting updated with each iteration of a loop within the function. The function code I have so far is below:
def vigenere(key, message):
message = message.lower()
message = message.replace(’ ‘,’')
m = len(key)
cipher_text = ‘’
for i in range(len(message)):
letter = message[i]
k = key[i] % m
cipher_text = cipher_text + chr((ord(letter) - 97 + k) % 26 + 97)
return cipher_text
Yes the key is a string, but with key[i] I am trying to represent the index value of the key variable that is active during the running loop iteration, i.e. if the key is “hello”, then on the first loop key[i] should return 0, and on the next loop key[i] should return 1, and so forth. I have tried to use multiple functions to return this value, such as int(), float(), and index(), but I cannot seem to find the right one. I have also tried converting the key to a list within the function to see if that would help, but it hasn’t.
I agree on checking the code more frequently throughout with prints. I’ve decided to brainstorm this and re-examine my lessons/code to potentially go another route. Thanks for the assistance everyone!