Reputation: 9
I'm having some difficulty trying to print out certain elements from a text file using a user's input.
I have a text file which displays the ID Number, Name of Desintation, ticket price, and the number of seats available as shown below respectively:
What I want is for the user to input either an ID Number or the Name of the Destination and the program will display the (1) corresponding destination (if an ID number was used) or to repeat the (2) name of the destination (if the name of the destination was used).
So i.e. user inputs Z6 and the program will show New York or if user enters New York, then New York will be printed again.
The below code is able to print out the corresponding destination for the ID Number; however, I can't seem to print out the name of the destination if a user inputs the name of the destination as I get a list index out of range error.
search = str (input ('Please enter the name or ID number of the destination:\n'))
info = open ('destinations.txt', 'r').readlines()
for I in info:
data = I.split (',')
if search == data[0]:
print (data[1])
elif search == data[1]:
print ([data[1])
Upvotes: 0
Views: 209
Reputation: 131
I copied your code and the only thing I had to fix was a syntax error on the last line: print([data[1])
has an extra open square bracket before data
. The following code worked correctly:
search = str (input ('Please enter the name or ID number of the destination:\n'))
info = open ('destinations.txt', 'r').readlines()
for I in info:
data = I.split (',')
if search == data[0]:
print (data[1])
elif search == data[1]:
print (data[1])
You can also combine the two conditions into one with an or
statement:
if search == data[0] or search == data[1]:
print(data[1])
Make sure that your destinations.txt
looks like this:
Z5,Melbourne,150,30
Z6,New York,120,60
Z9,Seoul,100,50
Z2,Tokyo,170,40
because this is the format your code is expecting.
Upvotes: 1