Name Search
If you have downloaded the source code from this book’s companion Web site, you will find the following files in the Chapter 08 folder:
• GirlNames.txt—This file contains a list of the 200 most popular names given to girls born in the United States from the year 2000 through 2009.
• BoyNames.txt—This file contains a list of the 200 most popular names given to boys born in the United States from the year 2000 through 2009.
Write a program that reads the contents of the two files into two separate lists. The user should be able to enter a boy’s name, a girl’s name, or both, and the application will display messages indicating whether the names were among the most popular. (You can access the book’s companion Web site at www.pearsonhighered.com/gaddis.)
Names Search Program Code:
#Reads the contents of the two files into two separate lists.
#The user should be able to enter a boy’s name, a girl’s name, or both,
#and the application will display messages indicating
#whether the names were among the most popular.
def readNamesFile(fileName):
try:
with open(fileName, "r") as file:
names = file.read().splitlines()
return names
except FileNotFoundError:
print(f"Error: {filename} not found.")
return []
def checkPopularity(names, name, gender):
if name in names:
print(f"The name '{name}' is popular for {gender}s.")
else:
print(f"The name '{name}' is not among the most popular {gender}s.")
# Read the contents of the files into separate lists
girlNames = readNamesFile("GirlNames.txt")
boyNames = readNamesFile("BoyNames.txt")
# Prompt the user for name input
girl_name = input("Enter a girl's name: ")
boy_name = input("Enter a boy's name: ")
# Check if the names are among the most popular
if girl_name:
checkPopularity(girlNames, girl_name, "girl")
if boy_name:
checkPopularity(boyNames, boy_name, "boy")
Data in "GirlNames.txt"—This file contains a list of the 200 most popular names given to girls born in the United States from the year 2000 through 2009:
Olivia
Emma
Charlotte
Amelia
Sophia
Isabella
Ava
Mia
Evelyn
Luna
Isabela
Jream
Cielo
Adalee
Sol
Wrenley
Zhuri
Scottie
Carla
Alora
Data in "BoyNames.txt"—This file contains a list of the 200 most popular names given to boys born in the United States from the year 2000 through 2009 is as follows:
Dutton
Kayce
Chosen
Khaza
Eithan
Waylen
Asaiah
Kaizen
Zen
Kylian
Ezrah
Eren
Amiri
Jrue
Kolson
Kanan
Colter
Teo
Koa
Zamir
Executed Output 1:
Enter a girl's name: Luna
Enter a boy's name: Teo
The name 'Luna ' is not among the most popular girls.
The name 'Teo' is popular for boys.
Executed Output 2:
Enter a girl's name: Carla
Enter a boy's name: John
The name 'Carla' is popular for girls.
The name 'John' is not among the most popular boys.