In: Computer Science
Please fix this python script, I keep getting a return outside function error and cannot get it to run:
def caesar(plainText, shift):
cipherText = ""
for char in plainText:
newChar = ord(char) + shift
if newChar > 128:
newChar = newChar % 128
finalChar = chr(newChar)
cipherText += finalChar
return cipherText
text = input("Enter a message: ");
s = input("Enter the distance value: ");
print (caesar(text, int(s)));
The problem with your code was bad indentation. The spacing was incorrect. Fixed it. Please find the updated code below.
def caesar(plainText, shift):
cipherText = ""
for char in plainText:
newChar = ord(char) + shift
if newChar > 128:
newChar = newChar % 128
finalChar = chr(newChar)
cipherText += finalChar
return cipherText
text = input("Enter a message: ");
s = input("Enter the distance value: ");
print (caesar(text, int(s)));
#end of code
But the above method lacks correctness. A better and correct method of implementing Caesar cipher would be as follows. Use this method if you want, else ignore it
def caesar(plainText, shift):
cipherText=""
#looping through each character
for char in plainText:
#checking if char is upper case
if char.isupper():
#checking if shifting will go beyond 'Z'
if (ord(char)+shift) > ord('Z'):
#finding how many spaces it will be moved away from 'Z'
index=ord(char)+shift-ord('Z')-1
#adding that distance to 'A' to get wrapped around, adding this
#value to cipherText
cipherText+=chr(ord('A')+index)
else:
#shifting normally
cipherText+=chr(ord(char)+shift)
elif char.islower():
#doing the same for lower case
if (ord(char)+shift) > ord('z'):
index=ord(char)+shift-ord('z')-1
cipherText+=chr(ord('a')+index)
else:
cipherText+=chr(ord(char)+shift)
else:
#other characters are not encrypted, simply appending to cipherText
cipherText+=char
#returning
return cipherText