gpt4 book ai didi

python - 在函数中返回一个列表。另外,还有 while 循环的问题

转载 作者:行者123 更新时间:2023-11-30 23:39:33 24 4
gpt4 key购买 nike

我在 Python 中创建函数时遇到问题。我希望我的功能允许用户在列表中输入单词,并询问用户是否愿意输入其他单词。如果用户输入“n”,我希望该函数返回列表中输入的单词。当我运行该函数时,它会询问用户是否愿意输入两次附加单词。此外,它不会返回列表。

def add_list(x):
first_list = raw_input('Please input a word to add to a list ')
x.append(first_list)
response = None
while response != 'n':
response = raw_input('Would you like to enter another word? ')
if response == 'n':
print 'Here is the list of words'
return x
else:
add_list(x)


def main():
add_list(x)


x = []
main()

最佳答案

如上所述,您的代码不返回任何内容的原因是您实际上并未打印结果。此外,即使您已经说了“n”,它仍然继续询问您是否要输入另一个单词的原因是递归(即您以嵌套方式一遍又一遍地调用该函数(想想Excel 中的嵌套 IF,如果有帮助的话:))。一旦你掌握了基础知识,你就可以阅读更多内容,但现在我会避免它:)

这是一个基本版本的东西,可以做你想做的事情,其中​​的注释有望帮助你理解正在发生的事情:

def add_list():
# Since you are starting with an empty list and immediately appending
# the response, you can actually cut out the middle man and create
# the list with the result of the response all at once (notice how
# it is wrapped in brackets - this just says 'make a list from the
# result of raw_input'
x = [raw_input('Please input a word to add to a list: ')]

# This is a slightly more idiomatic way of looping in this case. We
# are basically saying 'Keep this going until we break out of it in
# subsequent code (you can also say while 1 - same thing).
while True:
response = raw_input('Would you like to enter another word? ')

# Here we lowercase the response and take the first letter - if
# it is 'n', we return the value of our list; if not, we continue
if response.lower()[0] == 'n':
return x
else:
# This is the same concept as above - since we know that we
# want to continue, we append the result of raw_input to x.
# This will then continue the while loop, and we will be asked
# if we want to enter another word.
x.append(raw_input('Please input a word to add to the list: '))

def main():
# Here we return the result of the function and save it to my_list
my_list = add_list()

# Now you can do whatever you want with the list
print 'Here is the list of words: ', my_list

main()

关于python - 在函数中返回一个列表。另外,还有 while 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com