Reputation: 25
I'm trying to have the user input a telephone number, then the program will open a text file, convert it to a list, search the list and if the phone number is found it will return the rest of the line (which contains the address for that phone number.
I can only get it to return either "phone number not found" or the line but it does it for every single line so I end up with an output like this:
phone number not found
phone number not found
0121 254132 18 Springfield Road
phone number not found
phone number not found
for line in phonenumbers:
if number in line:
print (line)
else:
print ("phone number not found")
I know it's because I've put for line in phonenumbers but don't know how to not do it for every line.
Upvotes: 2
Views: 57
Reputation: 532
Why do you not just drop the else statement. It should look something like:
for line in phoneNumbers:
if phone in line:
print line
If you want a result in case that it was not found you could use a flag. moreover you can just use:
print [line for line in phonenumbers if number in line]
Upvotes: 0
Reputation: 1919
try the following:
for line in phonenumbers:
if number in line:
print (line)
break
else:
print ("phone number not found")
the else
is part of the for
loop and will only execute if you didn't break
out of the for
loop.
Upvotes: 4