for 循环在 while 循环下无法正常工作

时间:2021-04-18 15:36:28

标签: python python-3.x

我正在尝试创建一个程序,该程序从用户那里获取语句,然后在句子中应用问号和句号并将其组合成一个段落。 这是我到现在为止写的一些代码

Enter : Ray
Enter : What was that
Enter : \end
['Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Hi my name .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'Ray .', 'What was that ?', 'What was that .', 'What was that .', 'What was that .', 'What was that .', 'What was that .', 'What was that .', 'What was that .', 'What was that .', 'What was that .', 'What was that .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .', '\\end .']

Process finished with exit code 0
que = ('What', 'Where', 'Who', 'Which', 'Why', 'When', 'How', 'Whose', 'Am', 'Will', 'Is')
a = []
while True:
    statement = input("Enter : ")
    statement_list = statement.split()
    for i in que:
        if (i==statement_list[0]):
            a.append(statement + ' ?')
        else:
            a.append(statement + ' .')
    if statement == '\end':
        break

print(a)

1 个答案:

答案 0 :(得分:1)

尝试更多类似的东西。

que = ('What', 'Where', 'Who', 'Which', 'Why', 'When', 'How', 'Whose', 'Am', 'Will', 'Is')
a = []
while True:
    statement = input("Enter : ")
    if statement == '\end':
        break
    statement_list = statement.split()
    if statement_list[0] in que:
        a.append(statement + '?')
    else:
        a.append(statement + '.')

print(a)

我在这里做的不同之处在于,我正在检查用户输入的第一个单词是否在 que 中。如果是这样,我们现在可以肯定地知道,我们可以在末尾放一个 ?。假设用户输入的第一个词不在 que 中,我们将以 . 结束语句 此外,您在将语句附加到 \end 后检查用户是否输入了 a。相反,在将 \end 附加到您的列表之前,您检查用户是否输入了 \end,这样 \end 就不会出现在您的列表中。