简体   繁体   中英

Searching a list and displaying whether or not the list contains the search variable

I have a Twitter manager program where one option is searching for tweets containing whatever input the user provides. I am unable to figure out a way to have the for loop skip the else statement when there is a match found in the list. As it works now, the program will print the tweet it finds that matches the search criteria, but also prints that no tweet is found containing the search criteria.

# Option 3, search tweet_list for specific content and display if found
# in descending order starting with the most recent.
elif count == 3:
    tweet_list.reverse()
    if len(tweet_list) == 0:
        print('There are no tweets to search.', '\n')
    else:
        search = input('What would you like to search for? ')
        print('\nSearch Results')
        print('--------------')

        for n in tweet_list:
            a = n.get_author()
            b = n.get_text()
            c = n.get_age()

            if search in a or search in b:
                print(a + '-' + c + '\n' + b + '\n')                   

        else:
            print('No tweets contain "' + search + '".' + '\n')
            print('')

Create a variable, say found , and initialize it to False . When you find a tweet, set it to True . Then replace the else: with if not found: .

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