Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何预防;属性错误:';功能';对象没有属性''&引用;_Python_Function_Object_Attributeerror - Fatal编程技术网

Python 如何预防;属性错误:';功能';对象没有属性''&引用;

Python 如何预防;属性错误:';功能';对象没有属性''&引用;,python,function,object,attributeerror,Python,Function,Object,Attributeerror,我一直在开发一个程序,该程序旨在加密用户输入的消息。有两个加密选项,第二个选项用于使消息中的每个字符与字母表颠倒时的字符相同。当我输入消息时,会出现错误“AttributeError:“function”对象没有属性“find” 我的结构与第一个选项的代码类似,它运行时没有任何问题,我知道这个错误可能源于def语句,我不完全确定如何正确地进行结构 if option1 == 1: add = 13 message = raw_input('What message would you lik

我一直在开发一个程序,该程序旨在加密用户输入的消息。有两个加密选项,第二个选项用于使消息中的每个字符与字母表颠倒时的字符相同。当我输入消息时,会出现错误“AttributeError:“function”对象没有属性“find”

我的结构与第一个选项的代码类似,它运行时没有任何问题,我知道这个错误可能源于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)

我知道类似这样的问题在这个网站上经常被问到,但这些问题的答案对我没有帮助,因为我几乎没有编程经验。

您收到了一个错误,因为字母表是函数中定义的变量。因此,它是一个局部变量,不能在该函数之外访问

我很困惑,为什么一开始就有一个函数。我会将字母表函数下的所有内容替换为按顺序包含字符的变量

这段代码实际上有很多错误——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))

alphabet变量是局部变量,因此只能在alphabet()函数中调用它。当您放置
alphabet.find()
时,它认为字母表是函数,而不是变量

你可以做:

elif(option1 == 2):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    for char in message:
        print(alphabet[25-alphabet.find(char)])

这应该会起作用。

def alphabet():
我相信您编写的替换代码在解决此问题后会起作用,但在输入消息后,我得到的消息是“NameError:name'(消息)'未定义”。您也可以使用
str.ascii_小写字母。
elif(option1 == 2):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    for char in message:
        print(alphabet[25-alphabet.find(char)])