【问题标题】:TypeError: 'int' object is not subscriptable (nested functions)TypeError:“int”对象不可下标(嵌套函数)
【发布时间】:2017-08-08 07:54:30
【问题描述】:

所以,每当我调用一个调用另一个函数的函数时,我都会得到这个 TypeError 并且我不知道为什么,因为当我调用第一个函数时它不会发生。代码如下:

def codeChar(c,key):
    k = ord(c) + key
    if key > 26:
        key = key % 26
    if 91 <= k <= 96:
        k = k - 26
    elif 123 <= k:
        k = k - 26
    c = chr(k)
    return c

def codeBlock(word,key):
    i = 0
    result = ""
    while i < len(word):
        k = int(key[i])
        result = result + codeChar(word[i],k)
        i = i + 1
    return result

def isletter(h):
    i = ord(h)
    if 65 <= i <= 90:
        return True
    elif 97 <= i <= 122:
        return True
    else:
        return False

def codeString(string,key):
    i = 0
    result = ""
    while i < len(string):
        k = int(key[i])
        if isletter(string[i]) == True:
            result = result + codeBlock(string[i],k)
            i = i + 1
        else:
            i = i + 1
    return result

print(codeString(input("Enter a sentence to be coded: "),input("Enter an 8 digit key: ")))

运行时收到的错误代码是这样的:

Enter a sentence to be coded: Hello world
Enter your student number: 16061226
Traceback (most recent call last):
  File "E:\cw.1\cw.1.py", line 89, in <module>
    print(codeString(input("Enter a sentence to be coded: "),input("Enter your student number: ")))
  File "E:\cw.1\cw.1.py", line 82, in codeString
    result = result + codeBlock(string[i],k)
  File "E:\cw.1\cw.1.py", line 39, in codeBlock
    k = key[i]
TypeError: 'int' object is not subscriptable

提前致谢!

【问题讨论】:

  • 错误出现在哪里?整个错误消息是什么?
  • 刚刚加了,才发现忘记提了

标签: python function python-3.x int typeerror


【解决方案1】:

它与从另一个函数调用一个函数无关。当您从codeString 中调用codeBlock 时,您向它传递了一个参数k,它是一个整数。另一方面,在codeBlock 函数中使用key,您尝试通过执行int(key[i]) 来索引该整数,因此会出现typeError。

【讨论】:

    【解决方案2】:

    当您在第 36 行将 k 传递给 codeBlock 时,它是一个整数,而不是您的函数所期望的字符串。也许您打算在这里改用key

    【讨论】:

    • 当我使用 key 我收到 IndexError: string index is out of range for the result = result + codeBlock(string[i],key[i]) line
    • 这是由于您假设字符串比键短。如果字符串比键长,那么你会得到你描述的错误。
    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 2012-02-21
    • 2018-08-07
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多