In: Computer Science
Code is only reading the last line from the text files. How would I resolve? This is for the Name Search problem in Starting out with Python book. def main(): #open a file for reading infile = open('GirlNames.txt' , 'r') #Read the contents into a list Girls = infile.readlines() #open another file for reading infile = open('BoyNames.txt', 'r') #Read the contents into a lits Boys = infile.readlines() #Get a name to search for Name = input('Enter a name: ') #Determine if name is in list if Name in Girls or Name in Boys: print( Name, "is one of the popular names.") else: print(Name, "was not found in the list.") main()
Hello, here is the completed code you wanted. Every important statement is explained using comments. Please check and let me know if you have any doubts. Thanks.
CODE
def main():
#open a file for reading
infile = open('GirlNames.txt', 'r')
#readlines will read all names into list with a
newline character except last name
#splitlines will read all names into list without
newline character
#Read the contents into a list
Girls = infile.read().splitlines()
#open another file for reading
infile = open('BoyNames.txt', 'r')
#Read the contents into a list
Boys = infile.read().splitlines()
#Get a name to search for
Name = input('Enter a name: ')
#Determine if name is in list
if Name in Girls or Name in Boys:
print( Name, "is one of the popular
names.")
else:
print(Name, "was not found in the
list.")
main()
OUTPUT
CODE SCREEN SHOT
TEXT FILE SCREEN SHOT