【问题标题】:while loops not working for def() functionswhile 循环不适用于 def() 函数
【发布时间】:2018-03-03 20:51:33
【问题描述】:

我正在尝试一个程序,它将两个元素添加在一起以创建一个新元素,并且您必须在此过程中制作尽可能多的元素,例如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")

【问题讨论】:

  • 一般来说,你的整个代码片段没有什么意义。但是这个特殊的声明:pne.strip("[")(和下面的声明)没有做你认为他们正在做的事情。使用此功能前请阅读help(str.strip)

标签: python python-3.x


【解决方案1】:

总的来说,您的代码是个灾难。但是,让我们专注于您的直接问题。我猜是这样的:

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)

【讨论】:

  • 或者更好的def pnestuff(pne, de): 传递您想要使用的变量,而不是让函数对全局变量进行操作。
【解决方案2】:

我忘记将两个插入元素行放在 while 循环中。 掌心。感谢大家对 x.join 的帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2015-08-09
    • 2012-06-25
    • 2014-09-24
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多