Reputation: 919
In the first For Loop below, the code successfully shifts the letters num places to the right. The issue is in the second For Loop, it doesn't reverse it completely like it's supposed to. I've included output below. Any advice would be appreciated. Thanks
def cipher(message):
num = int(input())
final = []
finalReverse = []
for i in message:
if i.isalpha():
i = chr(ord(i)+num)
final.append(i)
if not i.isalpha():
final.append(i)
final = ''.join(map(str, final))
print(final)
for i in final:
if chr(ord(i)-num).isalpha:
x = chr(ord(i)-num)
finalReverse.append(x)
if not chr(ord(i)).isalpha:
finalReverse.append(char(ord(i)))
finalReverse = ''.join(map(str, finalReverse))
print(finalReverse)
cipher("The New York Times is in New York City.")
OUTPUT: (i entered number 3 for num)
1st For Loop's Output: Wkh Qhz \run Wlphv lv lq Qhz \run Flw||.
2nd For Loop's Output: TheNewYYorkTimesisinNewYYorkCityy+
Expected 2nd For Loop's Output: The New York Times is in New York City.
Upvotes: 1
Views: 356
Reputation: 7840
There are several problems here.
You should be using else
.
You follow if <condition>:
with if not <condition>:
. Instead, use else:
if i.isalpha():
i = chr(ord(i)+num)
final.append(i)
else:
final.append(i)
This isn't just cosmetic... since you change i
in the if
block, it's possible for both the if
and if not
blocks to run in a single iteration. Using else
solves this (and is better style anyway).
You forgot to call isalpha
in the decrypt section
You need to add parens to the end of your isalpha
calls in the decrypt section, otherwise only the if
block will ever run (because a method or function object is always considered true).
if chr(ord(i)-num).isalpha():
...
You used the wrong variable in your decrypt else
loop
You're appending x
to the list in the decrypt section's else
block, but x
only makes sense in the if
block. Use i
.
if chr(ord(i)-num).isalpha():
x = chr(ord(i)-num)
finalReverse.append(x)
else:
finalReverse.append(i)
Fixing those should produce your original message successfully.
Upvotes: 1
Reputation: 763
The answer is pretty simple. In first loop you didn't performed any conversion on spaces.
if not i.isalpha():
final.append(i)
But in second loop you are trying to convert spaces before appending to decryption list.
if not chr(ord(i)-num).isalpha:
finalReverse.append(x)
Also you are again appending x which is the value from upper condition .
finalReverse.append(x)
Instead of this you just have to append original value.
if not chr(ord(i)).isalpha:
finalReverse.append(char(ord(i)))
Let me know if you still have an issue.
Upvotes: 0