Python函数没有返回任何内容

时间:2016-05-28 20:18:01

标签: 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 can't have 2 weapons equipped!"
            x = ""
        print "\nYou equip the iron sword.\n"
        bag.remove("iron sword")
        bag_sword.append("iron sword")

当我第一次运行它时,它运行正常,但是当我第二次运行时没有任何反应。

bag_sword是一个列表

测试代码:

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'

我尝试使用变量代替input[]

(这不是语法)

2 个答案:

答案 0 :(得分:2)

以下是如何使函数按照描述工作的方法:

bag_sword = []

def equip(x):
    global bag_sword
    if x == "iron sword":
        if "iron sword" in bag_sword:
            print "You can't have 2 weapons equipped!"
        else:
            bag_sword.append("iron sword")

print bag_sword # Prints "[]".
equip("iron sword") # Prints nothing. Puts the string "iron sword" in bag_sword.
print bag_sword # Prints "['iron sword']".
equip("iron sword") # Prints "You can't have 2 weapons equipped!". bag_sword is unchanged.

答案 1 :(得分:0)

你可以使nwk的解决方案更通用(也试图摆脱全局变量):

git diff --cached HEAD~

在我看来,字典或类比几个包列表更好:

HEAD~