Reputation: 25
for i in pass_tmp:
if i % 2 == 0:
t = ord(i)
t = t + rot7
rotated_7 = chr(t
decrypted += i.replace(i, rotated_7)
else:
t = ord(i)
t = t + rot9
rotated_9 = chr(t)
decrypted += i.replace(i, rotated_9)
return decrypted
I am a learner of Python and this is an exercise that I'm doing during learning.
When running the code I am receiving the following error message "TypeError: not all arguments converted during string formatting" while referencing to the "if i % 2 == 0:" line in the code.
It works as it should until I add the "if i % 2 == 0:" line and have added the else code block. what i am trying to achieve is to separate the code to do different decoding depend on if the index of pass_tmp even or odd which "if i % 2 == 0" should take care of, it has worked before in every other exercise that I have had to use it but now it is not.
Upvotes: 0
Views: 52
Reputation: 83
If pass_tmp
is a string and you need both the character and its index you might want to use for i, char in enumerate(pass_tmp)
that way, i
will be the index and char
the character you can operate with. It would end up like this:
for i, char in enumerate(pass_tmp):
if i % 2 == 0:
t = ord(char)
t = t + rot7
rotated_7 = chr(t)
decrypted += char.replace(char, rotated_7)
else:
t = ord(char)
t = t + rot9
rotated_9 = chr(t)
decrypted += char.replace(char, rotated_9)
return decrypted
You are getting a typeError because the operation i % 2 == 0
is trying to get the modulus of dividing a string with an integer
Also since you are iterating one character at a time doing decrypted += i.replace(i, rotated_x)
is not necessary, you can optimize a little adding the new variable directly like decrypted += rotated_x
, something like:
for i, char in enumerate(pass_tmp):
if i % 2 == 0:
t = ord(char)
t = t + rot7
rotated_7 = chr(t)
decrypted += rotated_7
else:
t = ord(char)
t = t + rot9
rotated_9 = chr(t)
decrypted += rotated_9
return decrypted
Upvotes: 1