【发布时间】:2016-04-23 00:49:52
【问题描述】:
我对 python 还是很陌生,我正在做一个关于路径和文件的项目。不幸的是,我不能为那个项目发布我的代码,否则我会遇到麻烦。所以我做了一个类似于我希望用我的代码执行的练习问题,我想知道是否有人可以帮助我,因为我已经坚持了几天。
好的,所以我想做的是在验证第一个输入并输入第二个输入之后打印列表 L 中包含第二个输入的所有句子。前任。如果我有一个名为
的列表dog_sentences = ['dogs are cute', 'dogs are loyal', 'hi cat', 'dogs rule']
如果我的第二个输入是狗这个词。我希望它打印出列表中包含单词 dogs 的所有句子。所以我要打印的内容如下。
dogs are cute
dogs are loyal
dogs rule
这就是我希望能够在 shell 中打印的内容。所以这些是我做的练习题,并以两种不同的方式尝试过。
这是列表:
L=['hi there', 'it was nice to say hi', 'saying hi this many times is awkward',
'hey I can also say hola', 'no need to say hi']
第一种方式:
while True:
match = input().strip()
for sentence in L:
if match == 'Next' + ' ' + 'step':
print('match')
new_word_match = input().strip()
if new_word_match in sentence:
print(sentence)
break
else:
print('error')
但在 shell 中,它只是打印出列表中的第一句话,然后每次单击 enter 时都会继续输出错误。
第二种方式:
while True:
match = input().strip()
for sentence in L:
print(sentence)
if match == 'Next' + ' ' + 'step':
print('match')
new_word_match = input().strip()
if new_word_match in sentence:
print(sentence)
break
else:
print('error')
shell 只会给我最后一句话,即“无需打招呼”。但我要打印的是
hi there
it was nice to say hi
saying hi this many times is awkward
no need to say hi
如果有人可以帮助我,我将不胜感激,并在此先感谢您。
【问题讨论】:
-
那么你需要不断地接受这些输入吗?在这两个例子中你都有
while True。第二个有break,但第一个没有while循环。 -
因为我最初的问题是关于路径。我需要 while 循环,因为如果路径不存在,那么我需要打印单词 error,然后重复请求路径的过程,直到它有效。这就是我使用while循环的原因。我很抱歉没有早点写。
标签: python list if-statement input while-loop