尝试实现Caesar Cypher时出现一个奇怪的NameError

时间:2014-05-15 18:45:32

标签: python python-3.x

这是我到目前为止所做的事情,但这种情况不断出现:

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

我的代码:

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)

在最后一点,我认为这一切都出错,但我不知道为什么

1 个答案:

答案 0 :(得分:3)

似乎cypherText仅在您的函数内定义。

只需将您的功能修改为return

此外,由于caesar被定义为函数,因此需要调用它,否则其中的代码将无法运行。 请注意,我尚未测试您的caesar功能。 如果它被破坏,它仍将被破坏。

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))