在循环中返回输入

2024-06-16 12:08:44 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在尝试返回一个循环中的所有输入,但由于某种原因,这不起作用,它只返回最后一个输入

很高兴看到你帮助我

def boogiewoogie(lineinfile,speechpart):
    y = lineinfile.count(speechpart)
    for i in range(y):
        askuser = input('Enter '+speechpart+': ')
    return askuser

实际结果:

> boogiewoogie('The NOUN VERB past the ADJECTIVE NOUN.','NOUN')

> Enter NOUN:  dog
> Enter NOUN:  duck
> 'duck'

Tags: theinforinputreturndefcountrange
3条回答

由于没有数组或方法存储该值,因此会删除前一个值。创建一个空数组,然后将其附加到for循环中

List = []
for i in range(y):
       askuser = input('Enter '+speechpart+': ')
       List.append(askusr)
print List

在循环的每一轮中,你都在写askuser。尝试将所有值存储在列表中:

def boogiewoogie(lineinfile,speechpart):
    y = lineinfile.count(speechpart)
    askuser = []
    for i in range(y):
        askuser.append(input('Enter '+speechpart+': '))
    return askuser

你只返回最后一个,所以一切正常。您应该有,即list,将数据附加到列表中,然后返回该列表,类似于:

def boogiewoogie(lineinfile, speechpart):
    y = lineinfile.count(speechpart)
    history = []
    for i in range(y):
        history.append(input('Enter '+speechpart+': '))
    return history

将产生预期的:

Enter NOUN: dog
Enter NOUN: food
['dog', 'food']

出于可读性的原因,我也会放弃连接而选择format()

     history.append(input('Enter {}: '.format(speechpart)))

相关问题 更多 >