【问题标题】:Error message when no search result没有搜索结果时的错误消息
【发布时间】:2016-03-18 14:10:38
【问题描述】:

我制作了一个小程序,可以搜索 1975 年 -> Today 的 NYT 畅销书排行榜的标题。它工作得很好,但我试图在他们搜索的词中添加一条消息是找不到的。在下面的脚本中,如果没有结果,用户只会得到一个空行。我不知道该怎么做。

在倒数第六行,我尝试添加以下代码:

if title(s) == None:
    print "Sorry, your search gave no results."

但这不起作用。如果没有结果,我可以设置什么条件让程序打印错误消息?

这是输入文件的示例:

1876    Gore Vidal  Random House    4/11/1976   Fiction
23337   Stephen King    Scribner    11/27/2011  Fiction
1st to Die  James Patterson Little, Brown   3/25/2001   Fiction
2nd Chance  James Patterson Little, Brown   3/24/2002   Fiction
3rd Degree  James Patterson Little, Brown   3/21/2004   Fiction
4th of July James Patterson Little, Brown   5/22/2005   Fiction 

程序:

def title(s):
    f = open("bestsellers.txt", 'r')
    for line in f:
        list = line.split("\t")
        title = list[0]
        author = list[1]
        date = list[3]
        joinList = "".join(title)
        cleanList = joinList.lower()
        if s in cleanList:
            print "   %s, by %s (%s)" % (title, author, date)
    return

while True:
    print "\n"
    print "What would you like to do?"
    print "1: Search for title"
    print "Q: Quit"
    choice = raw_input(">")

    if choice == "q":
        print "Thank you come again"
        break

    elif choice == "1":
        while True:
            s_input = raw_input("Enter a title (or part of a title): ")
            s = s_input.lower()
            title(s)
            break

    else:
        print "Invalid choice. Please try again.\n"
        continue

【问题讨论】:

    标签: python


    【解决方案1】:

    试试这个:

    def title(s):
      f = open("bestsellers.txt", 'r')
      count = 0
      for line in f:
        list = line.split("\t")
        title = list[0]
        author = list[1]
        date = list[3]
        joinList = "".join(title)
        cleanList = joinList.lower()
        if s in cleanList:
            count = 1
            print "   %s, by %s (%s)" % (title, author, date)
      if count == 0:
        print "Sorry, your search gave no results."
    return
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      相关资源
      最近更新 更多