Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caesar's Cipher using python, could use a little help

Tags:

python

I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do main(3)

m
r
v
k
l
v
f
r
r
o

But it puts each letter on a new line. How could I do it so that it is on one line?

def main(k):

    if k<0 or k>231:
        print "complaint"
        raise SystemExit

    Input = raw_input("Please enter Plaintext to Cipher")

    for x in range(len(Input)):
        letter=Input[x]
        if letter.islower():
            x=ord(letter)
            x=x+k
            if x>122:
                x=x-122+97
            print chr(x),
        if letter.isupper():
            x=ord(letter)
            x=x+k
            if x>90:
                x=x-90+65
            print chr(x),

2 Answers

I like kaizer.se's answer, but I think I can simplify it using the string.maketrans function:

import string

first = raw_input("Please enter Plaintext to Cipher: ")
k = int(raw_input("Please enter the shift: "))

shifted_lowercase = ascii_lowercase[k:] + ascii_lowercase[:k]

translation_table = maketrans(ascii_lowercase, shifted_lowercase)

print first.translate(translation_table)
like image 192
Neil Vass Avatar answered Aug 10 '26 10:08

Neil Vass


This code should work pretty well. It also handles arbitrary offsets, including negative.

phrase = raw_input("Please enter plaintext to Cipher: ")
shift = int(raw_input("Please enter shift: "))

result = ''
for char in phrase:
    x = ord(char)

    if char.isalpha():
        x = x + shift

        offset = 65
        if char.islower():
            offset = 97

        while x < offset:
            x += 26

        while x > offset+25:
            x -= 26

        result += chr(x)

print result

The other way to do it, with a slightly different cipher, is simply rotate through all characters, upper and lower, or even all ascii > 0x20.

phrase = raw_input("Please enter plaintext to Cipher: ")
shift = int(raw_input("Please enter shift: "))

result = ''
for char in phrase:
    x = ord(char)

    x = x + shift

    while x < 32:
        x += 96

    while x > 127:
        x -= 96

    result += chr(x)

print result
like image 20
Jeff B Avatar answered Aug 10 '26 09:08

Jeff B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!