I need to create a ceasar cipher program that takes a string, converts it into ASCII, shifts it by 4, converts it back into a string, prints it, then deciphers it by reversing the cipher function, then prints the original string. However, The return value in my functions aren't working. How do I fix this? #cipher function
def cipher(string):
string = ""
NewX = 0
encrypted = 0
for letter in range(len(string)):
NewX = string[letter]
#encrypted is the encrypted word
encrypted = chr(ord(NewX) 4)
return encrypted
#Decipher function
def decipher(NewX):
NewString = ""
for letter in range(len(encrypted)):
NewString = chr(ord(encrypted)-4)
return(NewString)
def main():
string = input("enter your string here: ")
cipher(string)
print(encrypted)
decipher(NewX)
print()
main()
CodePudding user response:
There are quite a few errors in the code.
Indentation. In Python, blocks of code are indicated by how much the code is indented. In the decipher function,
NewString = ""
for letter in range(len(encrypted)):
NewString = chr(ord(encrypted)-4)
return(NewString)
The return
is one space too far to the right, or the lines above are one space too far to the left (more likely).
Concatenation. In the code, the result is declared to be empty, 0 or "" (and setting String
to "" blanks whatever string you input) . Then the idea, clearly, is to add to the end of the result the converted character. However, the code assigns the converted character instead, and over-writes whatever is there instead. A simple approach is to concatenate with the operator =
encrypted = chr(ord(NewX) 4)
Parameters. In the decipher function, the parameter passed in is NewX
, but the variable actually used is encrypted
. So this is the parameter that should have been passed in. Also, you're running ord
on the whole string, not on individual characters.
For loops. You can simply say:
for letter in string:
rather than
for letter in range(len(string)):
NewX = string[letter]
Return values. In the code, running the encypher and decipher functions are run, but since the results are not captured the results are thrown away.
With these errors corrected, the code is:
def cipher(string):
encrypted = ""
for letter in string:
#encrypted is the encrypted word
encrypted = chr(ord(NewX) 4)
return encrypted
#Decipher function
def decipher(encrypted):
NewString = ""
for letter in encrypted:
NewString = chr(ord(letter)-4)
return(NewString)
def main():
string = input("enter your string here: ")
encrypted=cipher(string)
print(encrypted)
decyphered=decipher(encrypted)
print(decyphered)
main()
CodePudding user response:
You would need to store the values the function is returning in a variable.
For example, in your main()
function block
encrypted= cipher(string)
print(encrypted) # Printing stored value
print(decipher(NewX)) # You can directly print it too without storing