Python总是打印其他的政治家

2024-05-23 19:41:08 发布

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

我有这样的代码:

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语句(文本文件中的第一行除外)

问题是:如何只打印找到的电影和电影,如果找不到电影,如何打印消息?你知道吗


Tags: thesearchif电影titlemoviesmovieelse
3条回答

使用^{}

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.")

您可以使用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

只有在for循环没有中断的情况下,else才会执行。通过这种方式,您可以添加以后运行的代码,无论是否找到电影(而不是立即返回)

必须确保迭代所有电影(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()

我建议只打印“NothingFound”,然后返回,而不是递归调用函数。你知道吗

相关问题 更多 >