user3642179
user3642179

Reputation: 3

Getting a strange NameError trying to implement a Caesar Cypher

This is what ive done so far but this keeps popping up:

Traceback (most recent call last):
  File "C:/Users/tom/Documents/python 2.py", line 20, in <module>
    print (cypherText)
NameError: name 'cypherText' is not defined

My code:

message = input("what is your message? ").lower()
Shift = int(input("What is your shift? "))

def caesar(message, shift):
    cypherText= " "
    for ch in message:
        if ch.isAlpha():
            stayInAlpha = ord(ch) + shift
        if stayInAlphabet > ord ('z'):
            stayInAlphabet -= 27
        if stayInAlphabet < ord ('a'):
            stayInAlphabet += 27
        finalletter = chr(stayInAlphabet)
        cypherText += finalletter



print ("Your message is:")
print (cypherText)

It is at this last bit where I think it all goes wrong but i have no idea why

Upvotes: 0

Views: 112

Answers (1)

merlin2011
merlin2011

Reputation: 75589

It appears that cypherText is defined only inside your function.

Just modify your function to return it.

Also, since caesar is defined as function, it needs to be invoked, or else the code inside it will not run. Note that I have not tested your caesar function. If it is broken, it will still be broken.

def caesar(message, shift):
    cypherText= " "
    for ch in message:
        if ch.isAlpha():
            stayInAlpha = ord(ch) + shift
        if stayInAlphabet > ord ('z'):
            stayInAlphabet -= 27
        if stayInAlphabet < ord ('a'):
            stayInAlphabet += 27
        finalletter = chr(stayInAlphabet)
        cypherText += finalletter
    return cypherText

print("Your message is")
print (caesar(message, Shift))

Upvotes: 3

Related Questions