why is this nearly same code producing different results

72 Views Asked by At

hello I am very new to coding and am working on a Caesar cipher. However for this code`

def encoder():
user_string=str(input('Enter text to encrypt'))
shift=int(input('Enter number to shift letters by'))
for i in range(len(user_string)):
    char=user_string[i]
    value=ord(char)
    new_value=value+shift
    new_value=chr(new_value)
    print(new_value,end='')
def decoder():
user_string=str(input('Enter text to decrypt'))
shift=int(input('Enter number to shift letters by'))
for i in range(len(user_string)):
    char=user_string[i]
    value=ord(char)
    new_value=value-shift
    new_value=chr(new_value)
    print(new_value,end='')

When I plug in something like Hello world it returns the correct result but with a # replacing the space. And when I plug in the encrypted result back into the decoder it returns the string with no spaces at all. The only difference between the two should be the use of newvalue = value + shift for the encoding and then newvalue = value-shift for the decryption. Can somebody help me understand why it is doing this and also how to fix the issue of the # in the encryption and no spaces in the decryption. Thank you. EDIT the shift value that I am using is 3 and the exact string is Hello world for the encryption and the encoded version of the same for the decryption.

1

There are 1 best solutions below

2
On BEST ANSWER

This is because space is also shifted by 3. Your program is absolutely correct.

The ASCII code for space is 32 and for # is 35.

encoder() with Hello world & 3 shift should result Khoor#zruogv

decoder() with Khoor#zruogv & 3 shift should result Hello world

If you want the space to not shift, and display as space, you can put an if statement inside the for loop.

for i in range(len(user_string)):
    char=user_string[i]
    if char == ' ':
        print(char, end='')
        continue
    value=ord(char)
    new_value=value+shift
    new_value=chr(new_value)
    print(new_value,end='')