Raspberry_Pi_Education_Manual

Notes:

Film search

# sort a file full of film names # function to compare the lowercase item with the searchfor def compare(item): return searchfor in item.lower() # load the file into a list and # close the file because the content is now in memory with open ( "filmlist" , "r" ) as film: filmlist = film.read().splitlines() searchfor = input ( "Enter part of the film \ name you are searching for: " ).lower().strip() # use the built-in filter function, which will # call the first parameter on every item on # the list and, if it is true, it will use the item foundlist = filter (compare, filmlist) for name in foundlist: print (name)

As in the previous experiment, the plan is to load a list of film names and then process them. In this case, the requirement is to find a film requested by the user.

The film list we created previously is loaded into memory. Text to “searchfor” is requested from the user. This is immediately converted to lowercase characters and any extra spaces stripped. During the search, any film title will also be converted to lowercase before checking so that case will not be relevant to the search. There is a Python function called “filter”, which will take a list and generate a new list by filtering out any entries that do not pass a test. In this case, our test will compare the user’s query text with the entry being tested. Long lines The input line has a “\” character half way through the question. This was added because the line was long. If the input question was typed on just one line, it would not need this character. A “\” character at the end of a line is a continuation marker. It indicates that the line hasn’t finished yet and it will continue on the next line of the program. When the program is run, this character won’t appear in the result – it is only used by the program interpreter to keep track of the flow of the code. Lastly, the entries in the list of found items are printed to the screen.

Experiments in Python

93

Made with FlippingBook flipbook maker