0

I'm doing a python exercise and writing my first function in which I have to return a value... But the value isn't being returned. I'm running the .py file through Terminal on OS X with Python 3.2.3. The final line should be different to the fourth final line, but they are coming out the same. Yet if I print textMessage in the function itself it prints fine. What am I missing?

def caesarEncipher(textMessage, shift):
    listOfChars = list(textMessage)
    length = len(listOfChars)
    count = 0
    while length != count:
        listOfChars[count] = chr(ord(listOfChars[count])+shift)
        count = count + 1
    textMessage = ''.join(listOfChars)
    return (textMessage)

print ("Please enter your message to cipher:")
textMessage = raw_input()
print ("Please enter the value you wish to shift your message by:") 
shift = int(input())
print "Your original message was:"
print textMessage
caesarEncipher(textMessage, shift)
print "Your message adjusted by a shift of", shift, "is:"
print textMessage
  • 4
    At the moment, this isn't a Caesar cipher. What happens if you try to shift the word `"zombie"` by 1? You'll get `"{pncjf"`. You need to shift *among letters*, not just increment the value that `ord` returns by `shift`. Think in terms of wraparound.. – DSM Jul 14 '12 at 17:55
  • Incidentally: `ceasarCipher = lambda msg, shift: ''.join(chr((ord(i)-97+shift) % 26 + 97) for i in msg.lower())` – Joel Cornett Jul 14 '12 at 21:01

4 Answers4

8

You need to save the value returned by your caesarEncipher() function.

So instead of this:

caesarEncipher(textMessage, shift)

have:

textMessage = caesarEncipher(textMessage, shift)

Right now the method is returning a value, but it's not being saved, and therefore can't be displayed in your subsequent print statement. Once you assign the return value of the function to a variable (in this case textMessage) you can use it.

Levon
  • 138,105
  • 33
  • 200
  • 191
6

It does. You have to catch it into a variable.

textMessage = caesarEncipher(textMessage, shift)

Anyway, Caesar would not encipher it this way. If you shift the value of the letter Z by a positive number, you are already out of the alphabet and returning some other characters.

You can use this method (works for lowercase characters only):

import string

def caesarEncipher(textMessage, shift):
    src_chars = string.lowercase
    dst_chars = string.lowercase[shift:] + string.lowercase[:shift]
    return textMessage.translate(string.maketrans(src_chars, dst_chars))
eumiro
  • 207,213
  • 34
  • 299
  • 261
1

You return the value. but you don't do anything with it. You need to store the returned value when you call the function:

textMessage = caesatEncipher(textMessage, shift)
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

You're never storing the return value of ceaserEncipher. To store the value, you do:

new_text_message=ceasarEncipher(textMessage,shift)
mgilson
  • 300,191
  • 65
  • 633
  • 696