在python中,我需要打印;“没有结果”;如果没有找到

在python中,我需要打印;“没有结果”;如果没有找到,python,Python,在搜索python文件时,如果没有找到结果,我需要能够打印“无结果” **strong text**elif x.upper()=="Y": k=input("Enter the 1st letter of the name (upper-Case):") y=open("Names.txt","r") for i in y.readlines(): if k.upper() in i: print (i[:-1])

在搜索python文件时,如果没有找到结果,我需要能够打印“无结果”

**strong text**elif x.upper()=="Y":
    k=input("Enter the 1st letter of the name (upper-Case):")
    y=open("Names.txt","r")
    for i in y.readlines():
        if k.upper() in i:
            print (i[:-1])
        #need option if no search results are found
您可以一次搜索整个文件。不是最好的性能,但足够简单。这是为了尽量减少对代码的更改。我会:

**strong text**elif x.upper()=="Y":
    k=input("Enter the 1st letter of the name (upper-Case):")
    y=open("Names.txt","r")
    all_text = y.read()
    for i in all_text.splitlines():
        if k.upper() in i:
            print (i) # don't need [:-1] anymore
        #need option if no search results are found
    found_f = k.upper() in all_text

那就去做吧。什么阻止了您?如果找到(在
if
中,类似于
found=True
),并且如果标记为false,则在
for
之外打印“无结果”,另一个选项是在for循环中添加一个else子句,并在print语句之后中断(仅当需要一个搜索结果时)。
**strong text**elif x.upper()=="Y":
    k=input("Enter the 1st letter of the name (upper-Case):")
    y=open("Names.txt","r")
    all_lines = y.readlines()
    for i in all_lines:
        if k.upper() in i:
            print (i[:-1])
        #need option if no search results are found
    found_f = k.upper() in ''.join(all_lines)
**strong text**elif x.upper()=="Y":
    k=input("Enter the 1st letter of the name (upper-Case):")
    y=open("Names.txt","r")
    all_text = y.read()
    for i in all_text.splitlines():
        if k.upper() in i:
            print (i) # don't need [:-1] anymore
        #need option if no search results are found
    found_f = k.upper() in all_text