else块不能正常工作

2024-03-29 05:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用python创建一个图书列表。你知道吗

以下是示例列表:

该列表包含图书标识、图书名称、writerName、writerSurname和成本对象。你知道吗

  books = [
     [45623, 'Ptyhon', 'Mustafa', 'Basak', 23],
     [99878, 'Linux Networks', 'Mustafa', 'Basak', 26],
     [98938, 'Operating Systems', 'Ali', 'Akinci', 17],
     [98947, 'PHP and AJAX', 'Haydar', 'Baskan', 25]
     ]

我想根据作者的姓氏搜索这个名单。你知道吗

 while 1:
     writerSurname = input('Pls enter the writer's surname.')
     if writerSurname not in ['exit', 'Exit']:
         for k in books:
             if str(writerSurname) == k[3]:
                 print(k[1],'writer', k[2],k[3], "cost is", k[4],"TL")

     else:
         print(writerSurname, 'there is no such a person.')
         break

但else块不能正常工作。当我键入一个不在图书列表中的姓氏时,它不会显示print(writerSurname,'没有这样的人')行。有人能告诉我哪里出错吗?你知道吗


Tags: in示例列表ifisbookselse标识
3条回答

除了无效语法之外,if语句并不关心姓氏是否在图书列表中:唯一要检查的是是否有一个类型exit/exit。你知道吗

您有缩进错误和一些逻辑错误。您的代码中的所有混乱不一定都是必需的,因此我将代码简化为:

books = [
     [45623, 'Ptyhon', 'Mustafa', 'Basak', 23],
     [99878, 'Linux Networks', 'Mustafa', 'Basak', 26],
     [98938, 'Operating Systems', 'Ali', 'Akinci', 17],
     [98947, 'PHP and AJAX', 'Haydar', 'Baskan', 25]
     ]

while True: 
    surname = input("pls enter the writer's surname: ") 
    for record in books:
        if surname in record:
            print("..details..")
            break 
    else: 
        print("Failed")

注意:如果你处理的是诸如姓名、数字等细节/记录,而且这些细节是相关的,并且你相信你会不断地搜索这些细节,我发现使用字典比在列表中线性搜索更快,更方便。你知道吗

while循环允许程序有多个条目,因此可以为程序输入无限多个名称。内部for循环执行实际的工作,在嵌入的列表中搜索姓氏(如果存在)。如果找到姓氏,print("...details...")将被执行,如果搜索了所有嵌入的列表,但没有找到匹配的姓氏,则print("Failed")将被执行。你知道吗

希望这对你有帮助,祝你好运!你知道吗

如果某些名称匹配,内部循环应该使用标志集

while True:
     writerSurname = input("Pls enter the writer's surname.")
     if writerSurname in ['exit', 'Exit']:
         break
     found = False
     for k in books:
         if writerSurname == k[3]:
             found = True
             print(k[1],'writer', k[2],k[3], "cost is", k[4],"TL")
     if not found:
         print(writerSurname, 'there is no such a person.')
         break

请注意,对于单个中断匹配(此处不适用),可以使用for/else语句:

 for k in books:
     if writerSurname == k[3]:
         print(k[1],'writer', k[2],k[3], "cost is", k[4],"TL")
         break
 else:
     # end of the loop reached, without break: enters here
     print(writerSurname, 'there is no such a person.')

相关问题 更多 >