while循环不适用于def()函数

时间:2018-03-03 20:51:33

标签: python python-3.x

我正在尝试将两个元素组合在一起制作新元素的程序,并且您必须在此过程中制作尽可能多的元素,例如https://littlealchemy.com/ 但我似乎无法让我的定义在while循环中重新运行。 当我运行它时,似乎不会将[]从列表中删除。更重要的是,它只运行一次,然后将终端留空。

很抱歉这些缩写,我更喜欢它,但如果需要,我可以更改它。

任何帮助将不胜感激。 三江源。

这是我的代码:

element1 = ""
element2 = ""
de = [] #discovered elements
ne = "" #new element
o1 = ""
o2 = ""
pne = ""

print("You have unlocked Fire, Water, Earth, and Air")
print("To see your unlocked elements, enter in 'menu' into the 'give the first element' option")

e1 = input("Give the first element ") #element 1
e2 = input("Give the second element ") #element 2

def pnestuff():
    pne = str(de); pne.strip("["); pne.strip("]")

def operate(x, y, z):
    global e1
    global e2
    o1 = (x)
    o2 = (y)
    ne = (z)
    if (e1 == o1 and e2 == o2) or (e1 == o2 and e2 == o1):
        de.append(ne)
        print("You have unlocked "+ne+"!")
        print("Your complete element list:")
        pnestuff()
        print(pne)
        e1 = ""
        e2 = ""

def menu():
    global e1
    global e2
    if e1 == "menu":
        print("You have unlocked:")
        pnestuff()
        print(pne)
        e1 = ""
        e2 = ""

#===============================================================================#

while 1:

    menu()

    operate("fire", "water", "steam")

2 个答案:

答案 0 :(得分:0)

总的来说,您的代码是一个灾难。但是,让我们关注你眼前的问题。我猜它是这样的:

def pnestuff():
    pne = str(de); pne.strip("["); pne.strip("]")

想要设置全局pne但未能将其声明为全局,并且无法理解字符串不可变

def pnestuff():
    global pne
    pne = str(de).lstrip("[").rstrip("]")

虽然更好的定义可能是:

def pnestuff():
    global pne
    pne = ', '.join(de)

答案 1 :(得分:0)

我忘了将两个插入元素行放在while循环中。 捂脸。并且谢谢大家对x.join的帮助