0

When a user enters an input and if it is not available, the print executes twice
How do I fix it???

if ask.lower() == 'open':
    with open(filename, 'r') as f:
        contents = f.read().splitlines()

    search_name = input("What is your name? ")
    for line in contents:
        if line.find(search_name) != -1:
            print(line)
        else:
            print("Unable to find your name")

output:

Unable to find your name
Unable to find your name

3
  • Check your input file, there could be more than one line present in it. Something like an empty line could be there in the file. Aug 6 at 5:58
  • You can just use f.readlines() instead of f.read().splitlines()
    – BeRT2me
    Aug 6 at 6:09
  • You might want to check if line has any significant content
    – Stuart
    Aug 6 at 6:34

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

0

Here is a more robust construct:

if ask.lower() == 'open':
    with open(filename) as f:
        name = input('What is your name? ')
        for line in f:
            if name in line:
                print(line)
                break
        else:
            print('Unable to find your name')
1
  • I agree. Anyhow, both of your answers helped me and this one is just more direct and concise.
    – Seth
    Aug 6 at 8:18
-1

You are invoking the print command for every entry in your file! Let me clarify, for the name that you get as input into search_name, you are looping over EVERY LINE that you have read from a file (in your case it seems that the file had 2 lines).

Your if cluase is not what you want. What you need is something like this:

if ask.lower() == 'open':
     with open(filename, 'r') as f:
        contents = f.read().splitlines()

search_name = input("What is your name? ")
is_found = false
for line in contents:
    if line.find(search_name) != -1:
        is_found = true
        print(line)

if not is_found:
    print("Unable to find your name")
1
  • I'm very surprised that this has been accepted as the definitive answer. Consider what happens if ask.lower() != 'open'
    – Stuart
    Aug 6 at 6:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.