Python 开发 [类型错误]

Python Development [Type Error]

我是初学者,最近开始 python 开发。 我正在处理的代码:

import random 
import textwrap

def show_message(dotted_line,width):

    print(dotted_line)
    print("3[1m"+ "Attack of clones:" + "3[0m")

    message = (
    "The war between humans and their arch enemies , Clones was in the offing. Obi-Wan, one of the brave Jedi on his way ," 
    "he spotted a small isolted settlement .Tired and hoping to replenish his food stock , he decided to take a detour." 
    "As he approached the village, he saw five residence , there was no one to be seen around.He decided to enter" )
    print(textwrap.fill(message, width = width))

def show_mission(dotted_line):
    print("3[1m"+ "Mission:" + "3[0m")
    print('\t Choose the hit where Obi wan can rest...')
    print("3[1m"+ "TIP:" + "3[0m")
    print("Be careful as there are Stormtroopers lurking around!")
    print(dotted_line)


def occupy_huts():
    global huts
    huts = []

    while len(huts) < 5:
        random_choice = random.choice(occupants)
        huts.append(random_choice)



def process_user_choice(): 
     message = "3[1m"+ "Choose the hut to enter (1-5) " + "3[0m"
     uc = input("\n" + message)
     index = int(uc)
     print("Revealing the occupants...")
     message = ""



def reveal_occcupants(index,huts,dotted_line):
    for i in range (len(huts)):
        occupant_info = "<%d:%s>"%(i+1,huts[i])
        if i + 1 == index:

            occipant_info = "3[1m"+ "" + "3[0m"
        message += occupant_info + " "
    print("\t" + message)
    print(dotted_line)



def enter_huts(index,huts,dotted_line): 
    print("3[1m"+ "Entering Hut %d ..." %index + "3[0m")

    if huts[index - 1] == 'clones':
        print("3[1m"+ "There's Stormtrooper Here!!" + "3[0m")
    else:
        print("3[1m"+ "It's Safe here!" + "3[0m")
    print(dotted_line)



def run():
    keep_playing = 'y'
    global occupants
    occupants = ['clones','friend','Jedi Hideout']
    width = 70
    dotted_line = '-' * width

    show_message(dotted_line, width)
    show_mission(dotted_line)

    while keep_playing == 'y':
         huts = occupy_huts()
         index = process_user_choice()
         reveal_occcupants(index,huts,dotted_line)
         enter_huts(index,huts,dotted_line)
         keep_playing = raw_input("Play Again?(y/n)")

if __name__ == '__main__':
    run()

错误在正文中 def reveal_occupants。 “TypeError:'NoneType' 类型的对象没有 len()

如何克服这个错误,也请提出替代方法

len() 方法接受一个对象作为参数。 在你的例子中,在第 43 行,小屋可能是 None,所以你会得到一个错误。

你应该在第 42 行之后插入如下 if 条件

if huts is None:
    return

我的猜测是 "huts" 是 None 类型,因为从未调用过 occupy_huts()。或者 "huts" 变量的范围存在问题——这可以通过在 occupy_huts() 函数之外将其声明为空集来解决。

此外,您可以利用 Python 的语法并将第 43 行更改为 "for hut in huts:"。如果您还需要小屋的索引,请尝试"for hut, i-hut in enumerate(huts):"。

您的方法 "reveal_occupants" 接收空值作为小屋。也就是说,那种类型的小屋是None。这就是为什么你不能得到这个值的 len 的原因。

这里:

while keep_playing == 'y':
     huts = occupy_huts()

你的 occupy_huts() 函数没有 return 任何东西(它填充全局变量 huts 但没有 return 它),所以 huts = occupy_huts() 语句 huts 现在是 None(默认函数 return 值,如果你没有明确地 return 某些东西)。然后你将这个(现在 Nonehuts 变量传递给 reveal_occupants() :

    reveal_occcupants(index,huts,dotted_line)

解决方案很简单:修改 occupy_huts,而不是在全局(这几乎总是一个非常糟糕的主意)和 returning None 上工作,它在一个局部变量和 returns 它:

def occupy_huts():
    huts = []
    while len(huts) < 5:
        random_choice = random.choice(occupants)
        huts.append(random_choice)
    return huts

当我们这样做时,您也在为 occupants 使用 global,这很脆弱(如果在创建此变量之前调用 occupy_huts() 将会中断),虽然您可以将其作为参数传递:

def occupy_huts(occupants):
    huts = []
    while len(huts) < 5:
        random_choice = random.choice(occupants)
        huts.append(random_choice)
    return huts

然后在 run():

def run():
    keep_playing = 'y'
    occupants = ['clones','friend','Jedi Hideout']
    # ...
    while keep_playing == 'y':
         huts = occupy_huts(occupants)

这里有趣的是,你传递的参数大多是常量并且对程序的逻辑没有影响(即 dotted_lines),但对重要的事情使用全局变量 - 应该真的是反过来(在模块的开头将 dotted_lines 声明为 pseudo_constant,不要费心将其传递给函数);)

此外,请注意您在此处遇到与 process_user_choice() 类似的问题:

while keep_playing == 'y':
     huts = occupy_huts()
     index = process_user_choice()

因为您的 process_user_choice() 函数也没有 return 任何东西。您应该对其进行修改,使其 return 成为其局部变量 index.