在 Python 中,如果没有找到,我需要打印"no results"



在搜索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")
found = False
for i in y.readlines():
    if k.upper() in i:
        print (i[:-1])
        found = True
if not found:
    print("no results")
**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

最新更新