Print Statement executing twice Python

Question:

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

Asked By: Seth

||

Answers:

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")
Answered By: Mostafa Najafiyazdi

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')
Answered By: Stuart
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.