Python Forum
Help printing any items that contains a keyword from a list
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help printing any items that contains a keyword from a list
#11
Yeah, that looks good. Just do it for each command. Then put it all into the while loop I described.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#12
Basically, yes. though your indentation is off.  All of your 'if' become 'elif' with the 'else' statement being the failsafe should all else fail.

While we're at it, this = not good

def menu(): print("l – load file of movie titles"'\n'"r – random movie"'\n'"s– search"'\n'""
      "sw – starts with"'\n'"k – keep - save the last displayed movie title to your favourites"'\n'"f – favourites display"'\n'""
      "c – clear"'\n'"q - quit program")
this = better

def menu():
    print("l – load file of movie titles\nr – random movie\ns– search\nsw – starts with\n"
          "k – keep - save the last displayed movie title to your favourites\nf – favourites display\nc – clear\n"
          "q - quit program")
This = bad

l = file = open("C:\\Users\\LiquidO\\Desktop\\Assingment 2 python\\movies.txt", "r")
if selection =='l':
    movies_list = file.readlines()
    movies_list = [movie.strip() for movie in movies_list]
    print("Movies now loaded")
Why assign to a variable 'l' plus you must manually close the file

This = better

if selection == 'l':
    with open("C:/Users/LiquidO/Desktop/Assignment 2 python/movies.txt", "r") as file:
        movies_list = file.readlines()
        movies_list = [movie.strip() for movie in movies_list]
        print("Movies now loaded")
File will be closed automatically.

Why assign a print function to 'r', and not use 'r'? Just print it.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#13
I edited the code a bit to make it a little easier hopefully. Although now im running into a problem with the keep function. It will work if used in the order of the commands but if I want to keep a random movie at say the second step it throws a
   (favourite[-1])
IndexError: list index out of range
My code now looks like this not sure if thats better or worse XD

import random
import sys
from random import choice, sample

print("***Movie Title Explorer***")


def menu(): print("l – load file of movie titles\nr – random movie\ns– search\nsw – starts with\n"
         "k – keep - save the last displayed movie title to your favourites\nf – favourites display\nc – clear\n"
         "q - quit program")

def rand ():
           print("Random choice selected")
           print(random.choice(movies_list))

def search():
   list = movies_list
   keyword = str(input("Search keyword: "))
   for movie in movies_list:
       if keyword in movie:
           print(movie)

def startsw():
       letter = str.upper(input("Search title starting with the letter: "))
       for movie in movies_list:
           if movie.startswith(letter):
               favourite.append(movie)
               print(movie)

def keep():
       favourite = []
       movies_list = favourite
       (favourite[-1])
       print("Last movie displayed saved to Favourites")

def showfav():
       print("Your Favourites List")
       print(movies_list[-1])

def clearfav():
       del favourite[:]
       print("Favourites List has been cleared")
def quit():
       print("Bye!")
       sys.exit()




menu()
print("command = ?")

selection=input("Please Select:")
l = file = open("C:\\Users\\LiquidO\\Desktop\\Assingment 2 python\\movies.txt", "r")
if selection =='l':
   movies_list = file.readlines()
   movies_list = [movie.strip() for movie in movies_list]
   print("Movies now loaded")
else:
   print ("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='r':
   rand ()
elif selection =='s': search()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print ("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='s':
   search()
elif selection =='r': rand()
elif selection =='s': search()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print ("Unknown Command")
menu()
favourite=[]
selection = input("Please Select:")
if selection =='sw':
   startsw()
elif selection =='s': search()
elif selection =='r': rand()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='k':
   keep()
elif selection =='s': search()
elif selection =='r': rand()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print ("Unknown Command")

menu()

selection = input("Please Select:")
if selection =='f':
   showfav()
elif selection =='s': search()
elif selection =='r': rand()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print ("Unknown Command")

menu()

selection = input("Please Select:")
if selection =='c':
   clearfav()
elif selection =='s': search()
elif selection =='r': rand()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print ("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='q':
   print("Bye!")
   sys.exit()
elif selection =='s': search()
elif selection =='r': rand()
elif selection =='k': keep()
elif selection =='f': showfav()
elif selection == 'q': quit()
else:
   print ("Unknown Command")
Reply
#14
You are repeating the same thing over and over again. Have the program do that for you. That's what loops are for.

while True:
    choice = input('Pick a letter: ').lower()
    if choice == 'a':
        print('The first letter')
    elif choice == 'z':
        print('The last letter')
    elif choice == 'q':
        break
    else:
        print('Some other letter')
Notice how I use lower. It's better to get it from the string you are lowering (the result of input) than to get it from the str class.

The problem with favorite is a scope problem. The favorite you define in a function only exists in that function. That's its scope. It is not the same as any favorite you define outside the function. What you want to do is return the value from the function:

def search(movie_list):
    keyword = input('Search keyword: ').lower()
    matches = []
    for movie in movies_list:
        if keyword in movie.lower():
            print(movie)
            matches.append(movie)
    return matches
First of all, notice how I pass movie_list as a parameter to the function. This is again about scope. That puts movie_list into the scope of the function. Note that I don't name things list or file. We have told you repeatedly that is a bad idea, and you haven't changed it. Those are keywords in Python, and if you change them it could mess up some other part of Python you are trying to make use of. Then I build a list of matches (as I showed you before), and return it from the function. When the function is called, it would look like this:

matches = search(movie_list)
Then you have the matches in the scope of the while loop. You can then add items from it to the favorites list that you defined in that same scope.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Collisions for items in a list Idents 3 2,252 Apr-06-2021, 03:48 PM
Last Post: deanhystad
  Removing items in a list cap510 3 2,308 Nov-01-2020, 09:53 PM
Last Post: cap510
  Help with Recursive solution,list items gianniskampanakis 8 3,506 Feb-28-2020, 03:36 PM
Last Post: gianniskampanakis
  Removing items from list slackerman73 8 4,342 Dec-13-2019, 05:39 PM
Last Post: Clunk_Head
  Find 'greater than' items in list johneven 2 4,428 Apr-05-2019, 07:22 AM
Last Post: perfringo
  How to add items within a list Mrocks22 2 2,640 Nov-01-2018, 08:46 PM
Last Post: Mrocks22
  printing list of random generated rectangles Zatoichi 8 7,283 Feb-18-2018, 06:34 PM
Last Post: buran
  How to keep duplicates and remove all other items in list? student8 1 4,914 Oct-28-2017, 05:52 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020