我一直在开发一个旨在加密用户输入的消息的程序。有两种加密选项,第二个加密选项旨在使消息中的每个字符与字母表颠倒后的内容相同。当我输入消息时,出现错误“AttributeError: 'function' object has no attribute 'find'”。
elif option1 == 2:
def alphabet():
alphabet = 'abcdefghijklmnopqrstuvwxyz'
'abcdefghijklmnopqrstuvwxyz'.reverse() == 'zyxwvutsrqponmlkjihgfedcba'
'abcdefghijklmnopqrstuvwxyz' [::-1] == 'zyxwvutsrqponmlkjihgfedcba'
message = raw_input('What message would you like to encrypt?')
message = raw_input('What message would you like to encrypt?')
for character in message:
position = alphabet.find(character)
newPosition = (position) % 26
newCharacter = alphabet[newPosition]
print(newCharacter)enter code here
我的结构与第一个选项的代码类似,运行时没有任何问题,并且我知道这个错误可能源于 def 语句,我不完全确定如何正确构建。
if option1 == 1:
add = 13
message = raw_input('What message would you like to encrypt?')
for character in message:
if character in alphabet:
position = alphabet.find(character)
newPosition = (position + add) % 26
newCharacter = alphabet[newPosition]
print(newCharacter)
我知道这个网站上经常有人问这样的问题,但这些问题的答案对我没有帮助,因为我的编程经验很少。
最佳答案
您收到错误,因为字母表是函数内定义的变量。因此,它是一个局部变量,无法在该函数之外访问。
我很困惑为什么那里有一个函数。我将用包含按顺序排列的字符的变量替换 Alphabet 函数下的所有内容。
这段代码实际上有很多问题 - for 循环中的代码也有缺陷。这是我的解决方案,其附加好处是将编码消息打印为一个字符串而不是一堆字符,以及处理非字母数字字符。
elif option1 == 2:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
message = input('What message would you like to encrypt?')
encoded = []
for character in message:
if character.isalpha():
encoded.append(alphabet[25-alphabet.find(character)])
else:
encoded.append(character)
print(''.join(encoded))
关于python - 如何防止 "AttributeError: '函数'对象没有属性 ''”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385940/