Hi, just beginning to learn Python, and am trying to create a script that will output matches from a text file to a user's input, I have managed that so far, the problem I have is trying to have something returned if the user puts in a string of text that does not match what is in the text file. ie - number not found. I have tried 'else', but it didn't work, I think I had put it in the wrong place.

Here's where I am at -

print"\nSEARCHING NUMBERS"

print "\nPlease Enter the Room Number 1, 2, 3, 4 or 5."

text_file = open("read_it.txt", "r")

word = raw_input("Type the Number you want to check: ")
word = word.upper()

print "\nnumber."
for line in text_file:

# if the line does not contain the typed word
# then continue to the next line

    if ''.join(line).find(word) == -1:continue    
    print line
print

if ''.join(line).find(word) != 1: 
    print line
print 

for line in text_file:
    print line

raw_input("\n\nPress the enter key to exit.")

text_file.close()

Any help/suggestions greatly appreciated.

M :-/

If I understand the problem, you want an else on the for loop, and do a break when you don't want it executed. Try something along these lines:

for line in text_file:

# if the line does not contain the typed word
# then continue to the next line

    if ''.join(line).find(word) == -1:continue    
    print line
    break
else:
    print "Not found" # Executed whenever break above is NOT executed
print

If you can't do the break at that spot in the code (e.g., because you need to go thru the entire loop, not just stop at the first match) then you'll have to do a little more work, but you should be able to figure that out :).

Thanks BearofNH, now giving it ago.
M:X

If I understand the problem, you want an else on the for loop, and do a break when you don't want it executed. Try something along these lines:

for line in text_file:

# if the line does not contain the typed word
# then continue to the next line

    if ''.join(line).find(word) == -1:continue    
    print line
    break
else:
    print "Not found" # Executed whenever break above is NOT executed
print

If you can't do the break at that spot in the code (e.g., because you need to go thru the entire loop, not just stop at the first match) then you'll have to do a little more work, but you should be able to figure that out :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.