我有这样的代码:
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
语句,它工作得“很好”,但如果我输入了不存在的电影,那么程序就会停止运行,很明显。你知道吗
如果我使用if
和else
,它将始终打印else
语句(文本文件中的第一行除外)
问题是:如何只打印找到的电影和电影,如果找不到电影,如何打印消息?你知道吗
使用^{} :
您可以使用python
for-else
:只有在
for
循环没有中断的情况下,else
才会执行。通过这种方式,您可以添加以后运行的代码,无论是否找到电影(而不是立即返回)必须确保迭代所有电影(
for i in movies
),直到可以确定是否找到了电影。所以:遍历所有电影,打印电影,如果找到它,就从函数返回。如果你在遍历了所有的电影之后还没有找到电影,那么请用户再试一次。你知道吗我建议只打印“NothingFound”,然后返回,而不是递归调用函数。你知道吗
相关问题 更多 >
编程相关推荐