如何从Python函数中返回列表

在 Python 中,可以轻松地从函数中返回一个列表。可以将列表直接作为返回值,通过 return 语句将其返回。

在这里插入图片描述

1、问题背景

在编写一个游戏时,需要创建一个函数来返回一个列表变量,以便将其传递给另一个变量。但是,在运行程序时遇到了错误,提示“TypeError: ‘NoneType’ object is unsubscriptable”。

2、解决方案

问题的原因在于startNewGame函数没有正确地返回列表变量。在该函数中,在创建列表变量MFCreatePH后,并没有使用return语句将其返回,而是直接打印了“Your PotatoHead varibles have been successfully created!”。

为了解决这个问题,需要在MFCreatePH创建后使用return语句将其返回,如下所示:

MFCreatePH = [inputPHName, inputPHGender, inputPHColour, inputPHFavThing, inputPHFirstToy]
return MFCreatePH

这样,startNewGame函数就可以正确地返回列表变量,并且可以被其他函数使用。

以下是修改后的代码:

def startNewGame():
    while 1:
        # Introduction:
        print()
        print("""Hello,
    You will now be guided through the setup process.
There are 7 steps to this.
You can cancel setup at any time by typing 'cancelSetup'
        Thankyou""")

        # Step 1 (Name):
        print()
        print("""Step 1 of 7:
    Type in a name for your PotatoHead:
    """)
        inputPHName = raw_input('|Enter Name:|')
        if inputPHName == 'cancelSetup':
            sys.exit()

        # Step 2 (Gender):
        print()
        print("""Step 2 of 7:
    Choose the gender of your PotatoHead:
                        input either 'm' or 'f'
    """)
        inputPHGender = raw_input('|Enter Gender:|')
        if inputPHGender == 'cancelSetup':
            sys.exit()

        # Step 3 (Colour):
        print()
        print("""Step 3 of 7:
    Choose the colour your PotatoHead will be:
                        Only Red, Blue, Green and Yellow are currently supported
    """)
        inputPHColour = raw_input('|Enter Colour:|')
        if inputPHColour == 'cancelSetup':
            sys.exit()

        # Step 4 (Favourite Thing):
        print()
        print("""Step 4 of 7:
    Type your PotatoHead's favourite thing:
    """)
        inputPHFavThing = raw_input('|Enter Favourite Thing:|')
        if inputPHFavThing == 'cancelSetup':
            sys.exit()

        # Step 5 (First Toy):
        print()
        print("""Step 5 of 7:
    Choose a first toy for your PotatoHead:
    """)
        inputPHFirstToy = raw_input('|Enter First Toy:|')
        if inputPHFirstToy == 'cancelSetup':
            sys.exit()

        # Step 6 (Check stats):
        while 1:
            print()
            print("""Step 6 of 7:
    Check the following details to make sure that they are correct:
    """)

            print()
            print("""Name:\t\t\t""" + inputPHName + """
Gender:\t\t\t""" + inputPHGender + """
Colour:\t\t\t""" + inputPHColour + """
Favourite Thing:\t""" + inputPHFavThing + """
First Toy:\t\t""" + inputPHFirstToy + """
""")

            print()
            print("Enter 'y' or 'n'")
            inputMCheckStats = raw_input('|Is this information correct?|')
            if inputMCheckStats == 'cancelSetup':
                sys.exit()
            elif inputMCheckStats == 'y':
                break
            elif inputMCheckStats == 'n':
                print("Re-enter info: ...")
                print()
                break
            else:
                "The value you entered was incorrect, please re-enter your choice"

        if inputMCheckStats == 'y':
            break

    # Step 7 (Define variables for the creation of the PotatoHead):
    MFCreatePH = []
    print()
    print("""Step 7 of 7:
    Your PotatoHead will now be created...

    Creating variables...
    """)

    MFCreatePH = [inputPHName, inputPHGender, inputPHColour, inputPHFavThing, inputPHFirstToy]
    time.sleep(1)
    print("inputPHName")
    print()
    time.sleep(1)
    print("inputPHFirstToy")
    print()

    return MFCreatePH

这样,就可以成功地将列表变量从startNewGame函数返回到其他函数中使用。

注意事项

  • 函数可以返回任意类型的数据,包括列表、字典、集合等。
  • 返回列表后可以在调用位置直接使用,例如 result[0] 访问第一个元素。

通过这种方式,Python 函数可以灵活地返回列表,便于数据处理和操作。

扫描二维码关注公众号,回复: 17504891 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_44617651/article/details/143573006