python - 使用列表来收集元素

标签 python list

我目前正在阅读《Learning Python The Hard Way》一书,我正在尝试制作一个简单的游戏。在这个游戏中,我希望能够在一个房间中拿起元素“手电筒”,以便能够进入另一个房间。然而,我不能让它工作:-(

所以问题是,如何通过多个函数携带同一个列表,以及如何将内容放入其中?我希望能够在其中放入多种内容。

我尝试在其内部调用 pick() 函数,但不断收到“TypeERROR: 'str' 不可调用,尽管我为我的函数提供了一个列表?

希望你能帮助我,谢谢:-)

代码:

def start(bag):
        print "You have entered a dark room"
        print "You can only see one door"
        print "Do you want to enter?"

        answer = raw_input(">")

        if answer == "yes":
            light_room(bag)
        elif answer == "no":
            print "You descidede to go home and cry!"
            exit()
        else:
            dead("That is not how we play!")

def light_room(bag):
    print "WOW, this room is amazing! You see magazines, cans of ass and a flashlight"
    print "What do you pick up?"
    print "1. Magazine"
    print "2. Cans of ass"
    print "3. Flashlight"

    pick(bag)

def pick(bag):    
    pick = raw_input(">")

    if int(pick) == 1:
        bag.append("Magazine")
        print "Your bag now contains: \n %r \n" % bag
    elif int(pick) == 2:
        bag.append("Can of ass")
        print "Your bag now contains: \n %r \n" % bag
    elif int(pick) == 3:
        bag.append("Flashlight")
        print "Your bag now contains: \n %r \n" % bag                    
    else:
        print "You are dead!"
        exit()

def start_bag(bag):
    if "flashlight" in bag:
        print "You have entered a dark room"
        print "But your flashlight allows you to see a secret door"
        print "Do you want to enter the 'secret' door og the 'same' door as before?"

        answer = raw_input(">")

        if answer == "secret":
            secret_room()
        elif answer == "same":
            dead("A rock hit your face!")
        else:
            print "Just doing your own thing! You got lost and died!"
            exit()
    else:
        start(bag)

def secret_room():
    print "Exciting!"
    exit() 

def dead(why):
    print why, "You suck!"
    exit()

bag = []
start(bag)

最佳答案

I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?

这里的问题是在这一行:

def pick(bag):    
    pick = raw_input(">")

您将 pick 绑定(bind)到一个新值(str),因此它不再引用函数。将其更改为:

def pick(bag):    
    picked = raw_input(">")

关于python - 使用列表来收集元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12302123/

相关文章:

python - 401 未经授权,来自 https ://test. pypi.org/legacy/

python - 无法删除 [未命名 :0] and NaN field data

Python:如何检查嵌套列表是否基本上为空?

list - SML-NJ 列表等于 Nil 与 Null 列表

python - 嵌套列表理解的奇怪行为

python - ax.xaxis.set_major_formatter 不会更改 Xtick 标签显示数字的数量

python - 自定义 API 不调用 has_object_permission

c# - 从 C# 中的 List<item> 中删除列表项后的行为

python - 在python中从一个列表中的另一个列表中查找元素

python - 如何将包含数学表达式的字符串拆分为列表?