In Python This assignment involves the use of text files, lists, and exception h
ID: 3727277 • Letter: I
Question
In Python
This assignment involves the use of text files, lists, and exception handling and is a continuation of the baby file assignment.
You should now have two files … one called boynames2014.txt and one called girlnames2014.txt - each containing the top 100 names for each gender from 2014. Write a program which allows the user to search your files for a boy or girl name and display where that name ranked in 2014. For example …
>>> Enter gender (boy/girl): boy Enter the name to search for: Michael Michael was ranked # 7 in 2014 for boy names. >>> ================================ RESTART ================================ Enter gender (boy/girl): boy Enter the name to search for: MIchAel MIchAel was ranked # 7 in 2014 for boy names. >>> ================================ RESTART ================================ Enter gender (boy/girl): boy Enter the name to search for: Jeremiah Jeremiah was ranked # 56 in 2014 for boy names. >>> ================================ RESTART ================================ Enter gender (boy/girl): girl Enter the name to search for: olivia olivia was ranked # 2 in 2014 for girl names. >>> ================================ RESTART ================================ Enter gender (boy/girl): girl Enter the name to search for: billie jean billie jean was not ranked in the top 100 girl names for 2014. >>> ================================ RESTART ================================ Enter gender (boy/girl): gril Enter the name to search for: sue Invalid gender >>>
Make sure to use try/except blocks to handle the exception if the files are not found or unavailable.
Use the index method on the list to find the baby name. Use a try/except block to handle the exception caused when the name is not found in the file.
Also, check for an invalid gender entry.
Make sure to include header comments and function comments in your program.
Explanation / Answer
def main(): boy_names = [] girl_names = [] try: with open('boynames2014.txt', 'r') as f: for name in f: boy_names.append(name.strip()) except FileNotFoundError: print('Error. Can not read from boynames2014.txt') return None try: with open('girlnames2014.txt', 'r') as f: for name in f: girl_names.append(name.strip()) except FileNotFoundError: print('Error. Can not read from girlnames2014.txt') return None gender = input('Enter gender (boy/girl): ') if gender == 'boy': lst = boy_names elif gender == 'girl': lst = girl_names else: print('Invalid gender') return None name = input('Enter the name to search for: ') try: index = lst.index(lst) print('%s was ranked #%d in 2014 for %s names.' % (name, index+1, gender)) except ValueError: print('%s was not ranked in the top 100 %s names for 2014.' % (name, gender)) main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.