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
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")
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')
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
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")
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')