Python总是打印else语句

时间:2017-12-16 01:17:15

标签: python if-statement text

我有这样的代码:

from tabulate import tabulate

def search_movie_title():
    movies = open('movies.txt','r').readlines()
    title = input("Input movie title: ").lower()
    for i in movies:
        movie = i.strip("\n").split("|")
        if title == movie[0].lower():
            table = [['Name:',movie[0]],['Genre:',movie[1]],['Running:',movie[2]],['Director:',movie[3]],['Starring:', movie[4]],['Country:', movie[5]], ['Realised:', movie[6]]]
            print (tabulate(table))
        else:
            print("Nothing found! Try again.")
            search_movie_title()

和这样的文本文件:

A fistful of Dolars|Western|100|Sergio Leone|Clint Eastwood|Italia|1964
For a few dolars more|Western|130|Sergio Leone|Clint Eastwood|Italia|1965
The Good, the Bad and the Ugly|Western|179|Sergio Leone|Clint Eastwood|Italia|1966
March on the Drina|War movie|107|Zika Mitrovic|LJuba Tadic|Serbia|1964

如果我只使用if语句,它可以正常工作"罚款",但是如果我输入不存在的电影,那么程序就会停止运行,显而易见。

如果我使用ifelse,它将始终打印else语句(文本文件中的第一行除外)

问题是:如果只打印finded和电影以及如果找不到电影怎么打印消息?

4 个答案:

答案 0 :(得分:4)

您可以使用python for-else

from tabulate import tabulate

def search_movie_title():
    movies = open('movies.txt','r').readlines()
    title = input("Input movie title: ").lower()
    for i in movies:
        movie = i.strip("\n").split("|")
        if title == movie[0].lower():
            table = [['Name:',movie[0]],['Genre:',movie[1]],['Running:',movie[2]],['Director:',movie[3]],['Starring:', movie[4]],['Country:', movie[5]], ['Realised:', movie[6]]]
            print (tabulate(table))
            break
    else:
        print("Nothing found! Try again.")

    # optionally add code here to be run regardless

只有在else循环未被破坏时才会执行for。这样,无论是否找到电影,您都可以在之后添加运行的代码(而不是立即返回)

答案 1 :(得分:1)

使用next

movie = next((movie for movie in movies
              if movie.split('|')[0] == title),
             None)

if movie:
    movie = movie.strip().split('|')
    fields = ['Name:', 'Genre:', 'Running:', 'Director:', 'Starring:', 'Country:', 'Realised:']
    table = list(zip(fields, movie))
    print (tabulate(table))
else:
    print("Nothing found! Try again.")

答案 2 :(得分:0)

您必须确保迭代所有电影(for i in movies),直到您可以决定是否找到电影。所以:迭代所有电影,打印电影并从函数返回,如果你找到它。如果您在迭代完所有电影后仍未找到该电影,请让用户再试一次。

from tabulate import tabulate

def search_movie_title():
    movies = open('movies.txt','r').readlines()
    title = input("Input movie title: ").lower()
    for i in movies:
        movie = i.strip("\n").split("|")
        if title == movie[0].lower():
            table = [['Name:',movie[0]],['Genre:',movie[1]],['Running:',movie[2]],['Director:',movie[3]],['Starring:', movie[4]],['Country:', movie[5]], ['Realised:', movie[6]]]
            print (tabulate(table))
            return

    print("Nothing found! Try again.")
    search_movie_title()

我建议只打印"没有找到"然后返回而不是递归地调用函数。

答案 3 :(得分:0)

每当您点击“其他”时,都会通过调用search_movie_title()重新开始搜索。除非您的搜索与movies的第一个条目匹配,否则您将处于else子句的无限循环中。

如果for循环完成而没有找到匹配项,则删除else并执行该块。