Trying to make an encrypter that shifts ascii values of each character in a message by the value of a corresponding character in a password - Output always results in either a single character or a string index out of range error:
msg = input()
pw = input()
pwN = 0
msgN = 0
for i in msg:
newmsg =""
nchar = chr(ord(msg[msgN]) + ord(pw[pwN]))
pwN += 1
msgN += 1
if pwN > len(pw):
pwN = 0
newmsg += nchar
print (newmsg)
Running it in this form results in a single character rather than a message length string in some cases, and in others gives me this error:
Traceback (most recent call last):
File "file", line 8, in <module>
nchar = str(chr(ord(msg[msgN]) + ord(pw[pwN])))
IndexError: string index out of range
I can't figure out what I'm missing.
The issue is that you're setting
newmsg
to the empty string in each loop. Movingnewmsg = ""
before thefor
loop should fix the issue of single characters, although figuring out the out of range error is difficult because of your manual increasing of several indices while also iterating overmsg
.I would suggest taking a look at the iteration features Python offers. You are technically iterating over
msg
, but never actually usei
, instead relying solely on indices. A more pythonic way to solve this might be as follows:if you want to stick to the loop. I would even use a generator expression to make it