简体   繁体   中英

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. 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 '". 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.

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. In the first method you simply reassigning the method to the e_key variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM