如何解决此代码中的类型错误?

问题描述

def turn_clockwise(point):
    all_point = ["N","E","S","W"]
    for loop in range[4]:
        if all_point[loop] == point:
            if loop == 3:
                return "N"
            else:
                return all_point[loop + 1]

来自 PyScripter 上 Python 解释器的消息:

回溯(最近一次调用最后一次):
文件“D:\Documents\Pyscripter 练习\Chp.6 练习 - 富有成效的函数.py”,第 25 行,在 test_suite()
文件“D:\Documents\Pyscripter 练习\Chp.6 练习 - 富有成效的函数.py”,第 21 行,在 test_suite test(turn_clock("N") == "E")
文件 《D:\Documents\Pyscripter 练习\Chp.6 练习 - 卓有成效 函数.py”,第 5 行,按 turn_clock 进行迭代 范围[4]:
类型错误:“类型”对象不可下标

解决方法

for loop in range(4) instead of range[4]

因为它从 0 迭代到 range-1

,

您需要使用 () 括号而不是 [] 因为 range 是我们需要调用的类。



def turn_clockwise(point):
    all_point = ["N","E","S","W"]
    for loop in range(4):
        if all_point[loop] == point:
            if loop == 3:
                return "N"
            else:
                return all_point[loop + 1]