Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Caesar Cipher Using Ord and Chr

Tags:

python

loops

I thought i've learned enough python to make a caesar cipher, so I started making it and i've hit a brick wall.

Here is my code:

phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")

for character in phrase:
    x = ord(character)

    x = x + shift


print chr(x)

At the moment if the phrase is 'hi' and shift is 1 , the for loop just loops around the letter i, not the letter h, so my result is: j

I want to loop around the whole word and shift each letter by whatever the shift int variable is.

How can I loop around the phrase variable?

like image 772
BubbleMonster Avatar asked Jul 17 '26 22:07

BubbleMonster


2 Answers

Your code is printing ord() value of 'j' because at the end of loop character is equal to 'i'. You should store the new characters to a list, and after the end of the loop you should join them and then print.

new_strs = []
for character in phrase:
    x = ord(character)
    x = x + shift
    new_strs.append(chr(x))   #store the new shifted character to the list
    #use this if you want z to shift to 'a'
    #new_strs.append(chr(x if 97 <= x <= 122 else 96 + x % 122))
print "".join(new_strs)       #print the new string

Demo:

$ python so.py
Enter text to Cipher: hi
Please enter shift: 1
ij
like image 192
Ashwini Chaudhary Avatar answered Jul 19 '26 12:07

Ashwini Chaudhary


Append each encrypted character to the result string.

phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ""

for character in phrase:
    x = ord(character)
    result += chr(x + shift)

print result
like image 27
falsetru Avatar answered Jul 19 '26 11:07

falsetru



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!