Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python函数不返回任何内容_Python_Python 2.7 - Fatal编程技术网

Python函数不返回任何内容

Python函数不返回任何内容,python,python-2.7,Python,Python 2.7,当我第一次运行它时,它工作得很好,但是当我第二次运行它时,什么都没有发生 包剑是一个列表 测试代码: def equip(x): global bag_sword global bag_chest global bag_gloves global bag_helmet while x == "iron sword" and "iron sword" in bag: if bag_sword: print "You c

当我第一次运行它时,它工作得很好,但是当我第二次运行它时,什么都没有发生

包剑
是一个列表

测试代码:

def equip(x):
    global bag_sword
    global bag_chest
    global bag_gloves
    global bag_helmet
    while x == "iron sword" and "iron sword" in bag:
        if bag_sword:
            print "You can't have 2 weapons equipped!"
            x = ""
        print "\nYou equip the iron sword.\n"
        bag.remove("iron sword")
        bag_sword.append("iron sword")
我试着用一个变量代替
input[]


(这不是语法)

以下是如何使函数按所述方式工作:

bag.append("iron sword")
if input1[:5] == "equip":
    print input1[:5]
    equip(input1[6:])
    print input1[6:]
I type into the console 'equip iron sword'

您可以使nwk的解决方案更通用(还可以尝试去除全局变量):

在我看来,一本字典或一门课似乎比几个书包清单更好:

def equip(item, bag):
    if item in bag:
        print "You can't have 2 {}s equipped!".format(item)
    else:
        bag.append(item)

def main():
    bag_sword = []
    print bag_sword
    equip("iron sword", bag_sword) 
    print bag_sword
    equip("iron sword", bag_sword)

if __name__ == '__main__':
    main()

您可以读取和修改全局变量,所以每次调用它时,它不必做同样的事情。你想发生什么?这应该做的是在没有任何武器的情况下为bag_剑添加一件武器,并告诉玩家如果已经有一把的话,他们就不能装备2把。我最后对你的做了一些调整来解决这个问题。我不知道为什么我用了一个while循环,我已经做了几天了,谢谢。
def equip(item, bag):
    if item in bag:
        print "You can't have 2 {}s equipped!".format(item)
    else:
        bag.append(item)

def main():
    bag_sword = []
    print bag_sword
    equip("iron sword", bag_sword) 
    print bag_sword
    equip("iron sword", bag_sword)

if __name__ == '__main__':
    main()
def equip(item, slot, inventory):
    if inventory[slot] == item:
        print 'Already equipped.'
    else:
        inventory[slot] = item
        print item.capitalize(), 'equipped.'

def main():
    inventory = {
        'weapon': None,
        'gloves': None,
        }

    equip('iron sword', 'weapon', inventory)
    print inventory
    equip('iron sword', 'weapon', inventory)

if __name__ == '__main__':
    main()