[英]Can anyone help me with this TypeError I keep getting in Python 2.7?
I am trying to make a program that converts a 5 letter string typed in by the user into a float using values stored in a dictionary to convert each letter. 我正在尝试制作一个程序,该程序使用用户存储在字典中的值将用户键入的5个字母的字符串转换为浮点数,以转换每个字母。 This is my code:
这是我的代码:
kvalues = {"a":1.01, "b":1.02, "c":1.03, "d":1.04, "e":1.05, "f":1.06, "g":1.07, "h":1.08, "i":1.09, "j":1.10, "k":1.11, "l":1.12, "m":1.13, "n":1.14, "o":1.15, "p":1.16, "q":1.17, "r":1.18, "s":1.19, "t":1.20, "u":1.21, "v":1.22, "w":1.23, "x":1.24, "y":1.25, "z":1.26}
def convert_key(key):
#converts the key into a float using the values stored in kvalues
k1 = float(kvalues.get(key[0]))
k2 = float(kvalues.get(key[1]))
k3 = float(kvalues.get(key[2]))
k4 = float(kvalues.get(key[3]))
k5 = float(kvalues.get(key[4]))
print k1 + k2 + k3 + k4 + k5
convert_key(raw_input (Please enter a key:))
When I run my program I get this error: "TypeError: 'builtin_function_or_method' object has no attribute ' getitem '". 当我运行程序时,出现以下错误:“ TypeError:'builtin_function_or_method'对象没有属性' getitem '”。 The really confusing part is when I run the code through the idle shell like this:
真正令人困惑的部分是当我像这样通过空闲外壳运行代码时:
key = "koala"
kvalues = {"a":1.01, "b":1.02, "c":1.03, "d":1.04, "e":1.05, "f":1.06, "g":1.07, "h":1.08, "i":1.09, "j":1.10, "k":1.11, "l":1.12, "m":1.13, "n":1.14, "o":1.15, "p":1.16, "q":1.17, "r":1.18, "s":1.19, "t":1.20, "u":1.21, "v":1.22, "w":1.23, "x":1.24, "y":1.25, "z":1.26}
k1 = float(kvalues.get(key[0]))
print k1
It works perfectly! 它完美地工作! Does anyone know what the issue here is?
有谁知道这里的问题是什么? I'm new to Python and not too familiar with the nuances of the language.
我是Python的新手,对这种语言的细微差别不太熟悉。
Here is the full traceback: 这是完整的回溯:
Traceback (most recent call last):
File "K:\Projects\koala.py", line 73, in <module> menu()
File "K:\Projects\koala.py", line 10, in menu encrypt()
File "K:\Projects\koala.py", line 28, in encrypt e_key = convert_key(e_key)
File "K:\Projects\koala.py", line 67, in convert_key k1 = float(kvalues.get(key[0]))
TypeError: 'builtin_function_or_method' object has no attribute 'getitem'
When print is added to the start of the function: 将打印添加到该功能的开始时:
<built-in method lower of str object at 0x0000000002AC7E40>
The issue is that somewhere you were doing this: 问题在于您正在执行此操作:
e_key = mystring.lower
When you meant to do this: 当您打算这样做时:
e_key = mystring.lower()
.lower
is a method , meaning it needs to be called like a function, so you need the parentheses. .lower
是一种方法 ,意味着需要像函数一样调用它,因此需要括号。 In the first method you simply reassigning the method to the e_key
variable. 在第一种方法中,您只需将方法重新分配给
e_key
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.