简体   繁体   中英

Python always print else statement

I have code like this:

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()

And text file like this:

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 I use use only if statement it works "fine", but if I input nonexistent movie, then program just stop running, obvious.

In case I use if and else it will always print else statement (except for first line in text file)

Question is: How to print only finded and also movie and how to print message if movie is not found?

You could make use of 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

the else will only be executed if the for loop was not broken. This way, you can add code afterwards that is run regardless of whether a movie was found or not (rather than immediately returning)

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

You must make sure to iterate over all movies ( for i in movies ) until you can decide if the movie was found or not. So: iterate over all movies, print the movie and return from the function if you find it. If you haven't found the movie after iterating over all them then ask the user to try again.

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()

I would suggest just printing "Nothing found" and then return instead of calling the function recursively though.

Every time you hit 'else', you restart the search by calling search_movie_title() . Unless your search matches on the first entry of movies , you'll be in an infinite loop of else-clause.

Remove the else and do that block if the for loop completes without finding a match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM