首页 > 解决方案 > 未定义名称凯撒密码

问题描述

我正在做一个关于 Caesar's Cypher 的练习,当我把它变成“纯代码”时我一切都很好,但是当我试图让它成为一个函数时,当我尝试在 Python Shell 中使用它时,我一直得到同样的错误。

有人可以解释一下为什么会发生这种情况,或者我应该改变什么才能使它起作用吗?

先感谢您

“普通”代码是:

alphabet = "abcdefghijklmnopqrstuvwxyz"

character = input("Please a character:")
displacement = int(input("Please enter a number:"))

position = alphabet.find(character)
newPosition = (position + displacement) % 26
newCharacter = alphabet[newPosition]

print(newCharacter)

我的功能是:

def cesar(character, displacement):
    """
    Receives a certain letter and a certain displacement size and codifies 
    that letter by giving it that displacement
    Requires: a letter from the alphabet with no variations (e.g:á,ê,õ) and 
    displacement > 0
    Ensures: a codified letter
    """
    alphabet = "abcdefghijklmnopqrstuvwxyz"

    position = alphabet.find(character)
    newPosition = (alphabet + displacement)%26
    newCharacter = alphabet[newPosition]
    return newCharacter

但是当我使用例如:

cesar(a,5)

我收到此错误:

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
cesar(a,5)
NameError: name 'a' is not defined

标签: pythonpython-3.x

解决方案


In [8]: def cesar(character, displacement):
   ...:     """
   ...:     Receives a certain letter and a certain displacement size and codifies 
   ...:     that letter by giving it that displacement
   ...:     Requires: a letter from the alphabet with no variations (e.g:á,ê,õ) and 
   ...:     displacement > 0
   ...:     Ensures: a codified letter
   ...:     """
   ...:     alphabet = "abcdefghijklmnopqrstuvwxyz"
   ...: 
   ...:     position = alphabet.find(character)
   ...:     newPosition = (position + displacement)%26
   ...:     newCharacter = alphabet[newPosition]
   ...:     return newCharacter

这样做,然后调用:

cesar('a',5)


推荐阅读