Search code examples
python-3.xprintingcaesar-cipher

printing Caesar cipher at once


def en(password,shift):
    result = ""
    for i in password:
        result += chr(ord(i)+ shift)
    return result
def de(password,shift):
    result = ""
    for i in password:
        result += chr(ord(i) - shift)
    return result
n=input("Input : ")
s=int(input("shift number :  "))
e=en(n,s)
print("encoded : "+e)
print("decoded : "+de(e,s))

This is the method getting Caesar cipher

I can't solve. How to print using 'shift number' -30~30 at once?


Solution

  • There are three things you haven't dealt with:

    1) Letter case -- upper and lower case letters have to massaged slightly differently.

    2) Non-letters -- non alphabetics should probably pass through unchallenged.

    3) Modular arithmetic -- when you add a shift to a letter, you might fall off the end of the alphabet so you need to wrap around to the beginnning like a clock. The reverse happens when you decode.

    Consider this example as you update your code:

    % python3 test.py
    Input: Veni, vidi, vici
    Shift number: 13
    encoded: Irav, ivqv, ivpv
    decoded: Veni, vidi, vici
    %