954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Validating user input against text file

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 :-/

myself2211
Newbie Poster
2 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

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 thebreak 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 :).

BearofNH
Posting Whiz
323 posts since May 2007
Reputation Points: 94
Solved Threads: 48
 

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 thebreak 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 :).

myself2211
Newbie Poster
2 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You