需要有关循环我的代码的帮助,以便重复而不是搜索一次

时间:2017-05-16 02:22:38

标签: python loops

我不知道如何制作这个循环

term = input("")
file = open('file.txt')
for line in file:
    line.strip().split('/n')
    if term in line:
        print(line)
    if term in line:
        print('Not on database, (try using caps)')
file.close()

(我知道这是不正确的)

3 个答案:

答案 0 :(得分:0)

如果通过“重复”表示您希望用户能够多次输入一个术语,那么只需使用while循环。

while True:
    term = input("")
    file = open('file.txt')
    for line in file:
        line.strip().split('/n')
        if term in line:
            print(line)
        if term in line:
            print('Not on database, (try using caps)')
    file.close()

我不确定你想要循环多少次,但这个循环将无限期地进行。

答案 1 :(得分:0)

我猜你需要的是这个。

term = input("")
# file is a python object by default, so it's better not to use it.
f = open('file.txt')
# Put each line in the file into a list
content = f.readlines()
for line in content:
    # str.strip() does not replace the original string
    # I modify it so that it is replaced.
    line = line.strip()
    if term in line:
        print(line)
    # The line below is unnecessary because it's the same condition as the previous if statement
    # if term in line:
        print('Not on database, (try using caps)')
f.close()

答案 2 :(得分:0)

您可以使用with打开文件并循环播放。

term = input("")
with open('file.text') as f:
    for line in f.readlines():
        if term in line.strip():
            print(line)
            break #breaks for loop and exits