 <pre><code>def transcript_search(search_parameter,files): for line in files: if search_parameter in line: return line else: print('Invalid entry') files = open('/Users/labadmin/Desktop/example.gtf', 'r') gene_id = input("Enter the gene_id:") transcript_search(gene_id,files) </code></pre> <p>Don't use file. As that is a python keyword. You also need to pass in the file to the function.</p> <p>Also are you sure when it's invalid you want to print but not return anything? The return type would be <code>None</code>. Could be what you want so I didn't change it.</p> <p>To print invalid only once:</p> <pre><code>def transcript_search(search_parameter,files): for line in files: if search_parameter in line: return line #In this way invalid will only print after it has gone through all the lines and never returned. print('Invalid entry') </code></pre> <p>As for saving:</p> <pre><code>saved_lines = [] files = open('/Users/labadmin/Desktop/example.gtf', 'r') gene_id = input("Enter the gene_id:") #Append to list the saved entries. saved_lines.append(transcript_search(gene_id,files)) </code></pre> <p>After which you write all of the list to a line using <code>files.writelines(list)</code> or print them to screen or whatever you want.</p> <p>This adds all the lines with ur search_parameter to a list and returns the list</p> <pre><code>def transcript_search(search_parameter,files): toreturn = [] for line in files: if search_parameter in line: toreturn.append(line) if len(toreturn)&gt;0: #Notice at how this returns an array of strings instead of one string. return toreturn print('Invalid entry') </code></pre>