0

I'm making a Caesar cipher program for class, I know this isn't the neatest way of doing it but it does work, my question is, for the if/else bit in the middle, is there a better way than having newcode=newcode in the else sections? Seems v clunky but im a complete newb and its the first way i thought of

plaintext = input("Input your message here: ")
shift = input("Input cyclic shift here: ")
message = ""

try:
    shiftn = int(shift)
except ValueError:
    print("Cyclic shift must be a number")
else:
    for i in plaintext:
        code = ord(i)
        if (32<=code<=47) or (58<=code<=64):
            newl = chr(code)
            message = message + newl
        elif (65<=code<=90):
            newcode = code + shiftn
            if newcode > 90:
                newcode = 64 + (newcode - 90)
            else:
                newcode=newcode
            newl = chr(newcode)
            message = message + newl
        elif (97<=code<=122):
            newcode = code + shiftn
            if newcode > 122:
                newcode = 96 + (newcode - 122)
            else:
                newcode = newcode
            newl = chr(newcode)
            message = message + newl
        elif (48<=code<=57):
            newcode = code + shiftn
            if newcode > 57:
                newcode = 47 + (newcode - 57)
            else:
                newcode = newcode
            newl = chr(newcode)
            message = message + newl
    print("your encrypted message is: ", message)
Amy Fawcett
  • 107
  • 5

1 Answers1

3

Since the code is the same for all the different ranges, you can just put those in a list and loop over the list, breaking after the first match. Also, the else is redundant, as is chr(ord(i)).

for i in plaintext:
    code = ord(i)
    if (32 <= code <= 47) or (58 <= code <= 64):
        message += i
    else:
        for low, high in [(64, 90), (96, 122), (47, 57)]:
            if low < code <= high:
                newcode = code + shiftn
                if newcode > high:
                    newcode = low + (newcode - high)
                message += chr(newcode)
                break

Also, you are sort-of reinventing modulo % here, and could also calculate newcode like this (not sure if that's simpler, though):

                newcode = (code + shiftn - low) % (high - low) + low
tobias_k
  • 81,265
  • 12
  • 120
  • 179