Python开发[类型错误]

2024-05-26 07:46:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初学者,最近开始了python开发。 我正在研究的代码:

import random 
import textwrap

def show_message(dotted_line,width):

    print(dotted_line)
    print("\033[1m"+ "Attack of clones:" + "\033[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("\033[1m"+ "Mission:" + "\033[0m")
    print('\t Choose the hit where Obi wan can rest...')
    print("\033[1m"+ "TIP:" + "\033[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 = "\033[1m"+ "Choose the hut to enter (1-5) " + "\033[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 = "\033[1m"+ "" + "\033[0m"
        message += occupant_info + " "
    print("\t" + message)
    print(dotted_line)



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

    if huts[index - 1] == 'clones':
        print("\033[1m"+ "There's Stormtrooper Here!!" + "\033[0m")
    else:
        print("\033[1m"+ "It's Safe here!" + "\033[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显示乘员。 “类型错误:类型为'NoneType'的对象没有len()

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


Tags: thetomessageindexdefshowlinerandom
3条回答

len()方法接受对象作为参数。 在您的例子中,在第43行,huts可能没有,因此您可能会得到一个错误。你知道吗

您应该在第42行后插入如下条件

if huts is None:
    return

我的猜测是“huts”不是类型,因为从来没有调用过occupt_huts()。或者“huts”变量的作用域有问题——这可以通过将其声明为函数的一个空集来解决。你知道吗

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

此处:

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

您的occupy_huts()函数不返回任何内容(它填充了一个全局变量huts,但不返回它),因此huts = occupy_huts()语句huts后面的现在是None(如果您不显式返回某些内容,则为默认函数返回值)。然后将这个(现在是Nonehuts变量传递给reveal_occupants()

    reveal_occcupants(index,huts,dotted_line)

解决方案很简单:修改occupy_huts,因此它不处理全局变量(这几乎总是一个非常糟糕的主意)并返回None,而是处理局部变量并返回它:

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

当我们使用它时,您也在使用global来表示occupants,这是脆弱的(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),但是对重要的事情使用全局变量-实际上应该是相反的方式(在你的模块开始时声明虚线为伪常量,不用麻烦把它传递给函数);)你知道吗

另外,请注意,这里的process_user_choice()也有类似的问题:

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

因为process_user_choice()函数也不返回任何内容。您应该修改它,使它返回其局部变量index。你知道吗

相关问题 更多 >