是我尝试过的功能:
def function(x):
list1 = []
if("word" in x):
print("Option 1: XXX, Option 2: YYY ...")
list1.extend(input("Enter a word: "))
我在这里尝试做的是将值X放在我选择的字符串中(向用户提出问题)并让用户输入他们的答案。然后我想将这个答案添加到 NOT 一个全局变量的列表中(因为这是我要避免的要点),而不是每次调用此函数时都要擦除该列表;因为我希望多次将函数(x)称为几个问题。完成此操作后,我还需要能够拉出此列表并将其传递给另一个函数,以便可以对用户的答案进行数学运算等。
有什么建议吗?如果你能解释正在发生的事情,我会非常感激,因为我正在努力去理解这里发生的事情。我被告知将列表放在函数参数中是有效的(并且确实如此),但这不允许我以后获取列表并对其执行操作(并且显然是python中的错误)。为此运行循环也没有多大帮助。
编辑:我会在几个小时后回来,然后会给出答案;还没有读过所有这些,但到目前为止,我认为我正在处理它。答案 0 :(得分:2)
您可以使用return
来避免使用global
变量
def function(x):
answer = "n/a"
if("word" in x): # test if x contains "word", not sure why you have this
print("Option 1: XXX, Option 2: YYY ...")
answer = input("Enter a word: ")
return answer # this is the value given when the function is called
list1 = []
list1.append(function("...")) # add the value returned by the function
list1.append(function("..."))
...
答案 1 :(得分:2)
我认为您所寻找的内容在C语言中称为static
.Python不需要这样的关键字,因为它非常灵活。实现它的一种方法是使用闭包来维护封装。您会注意到setupf
函数返回两个内部函数,其名称可以是任何合法的函数。
def setupf():
list1 = [] # This is the "static" variable
def internal(x):
if ("word" in x):
print("Option 1: XXX, Option 2: YYY ...")
list1.append(input("Enter a word: "))
def getit():
return list1
return internal, getit
function, getlist = setupf()
function("word")
function("word")
function("word")
function("word")
print(getlist())
给出:
Option 1: XXX, Option 2: YYY ...
Enter a word: hello
Option 1: XXX, Option 2: YYY ...
Enter a word: goodbye
Option 1: XXX, Option 2: YYY ...
Enter a word: stuff
Option 1: XXX, Option 2: YYY ...
Enter a word: another
['hello', 'goodbye', 'stuff', 'another']
您可能会注意到我将.extend
替换为.append
- 在使用.append
的Python的C实现中,由于列表的实现方式,效率更高。
我对#34;字"的测试感到困惑,也许你可以解释一下。