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

How do I resolve a type error in this code?

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 解释器的消息:

Traceback (most recent call last):
File "D:\Documents\Pyscripter practice\Chp.6 Exercises - Fruitful functions.py", line 25, in test_suite()
File "D:\Documents\Pyscripter practice\Chp.6 Exercises - Fruitful functions.py", line 21, in test_suite test(turn_clockwise("N") == "E")
File "D:\Documents\Pyscripter practice\Chp.6 Exercises - Fruitful functions.py", line 5, in turn_clockwise for iteration in range[4]:
TypeError: 'type' object is not subscriptable

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

因为它从 0 迭代到范围 1

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



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]