python - 未定义名称凯撒密码
问题描述
我正在做一个关于 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
解决方案
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)
推荐阅读
- docker - 有没有办法在默认情况下使用 docker compose 构建而没有 --parallel ?
- r - 编写良好数据集以执行混合模型分析的棘手方法
- python - 如何在 Mac 上离线运行 VPython
- pandas - 迭代 Pandas DataFrame 的重复分区/组
- json - 我如何阅读这个 json 并迅速将其更改为字典?
- c++ - 需要一些关于 C++ 中“交换”函数的帮助
- javascript - Mat-Error 首次打开表单时显示必需的验证错误消息
- c++ - 使用 for 循环的 C++ 中的分段错误
- c# - WPF Datagrid 列标题中的文本框过滤器
- html - 如何在 Visual Studio Code 中设置默认浏览器?