-2

I am trying to implement a Caesar cipher.

I have tried to return message in the function, but I get an error message (outside function). Can anyone help, please?

Thanks in advance

cat
cate
catec
catecv

message = input("type message ")

shift = int(input("Enter number to code "))
message = message.lower() #convets to lower case
print (message)

for a in message:
    if a in "abcdefghijklmnopqrstuvwxyz":
        number = ord(a)
        number += shift
        if number > ord("z"):
            number -= 26
        elif number < ord("a"):
             number += 26
        message = message + (chr  ( number))

    print (message)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Wayne Askey
  • 13
  • 1
  • 4
  • _"I have tried to return message in the function"_. You don't appear to have a function here. Functions start with `def`. If you don't have `def`, you can't have `return`. – Kevin Oct 14 '14 at 19:48
  • 2
    Could you copy/paste the traceback of the error you're getting? That would be helpful. – PolskiPhysics Oct 14 '14 at 19:51
  • 1
    I suspect the full error message is `SyntaxError: 'return' outside function`, and it occurred in a different version of the OP's code that used `return`. – Kevin Oct 14 '14 at 19:54

1 Answers1

8

Here's Python 3 Caesar cipher implementation that uses str.translate():

#!/usr/bin/env python3
import string

def caesar(plaintext, shift, alphabet=string.ascii_lowercase):
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    return plaintext.translate(plaintext.maketrans(alphabet, shifted_alphabet))

message = input("type message to encode")
shift = int(input("Enter number to code "))
print(caesar(message.lower(), shift))

Here's Python 2 version of Caesar Cipher.

TigerTV.ru
  • 1,058
  • 2
  • 16
  • 34
jfs
  • 399,953
  • 195
  • 994
  • 1,670