rahmad akbar wrote: > hey again guys, i am trying to understand these statements, > > if i do it like this, it will only print the 'print locus' part > > for element in in_file: > if element.find('LOCUS'): > locus += element > elif element.find('ACCESSION'): > accession += element > elif element.find('ORGANISM'): > organism += element > > print locus > print accession > print organism > > > once i add >= 0 to each if conditions like so, the entire loop works and > prints the 3 items > > for element in in_file: > if element.find('LOCUS') >= 0: > locus += element > elif element.find('ACCESSION') >= 0: > accession += element > elif element.find('ORGANISM') >= 0: > organism += element > > print locus > print accession > print organism > > why without '>= 0' the loop doesnt works?
element.find(some_string) returns the position of some_string in element, or -1 if some_string doesn't occur in element. All integers but 0 are true in a boolean context, i. e. if -1: print -1 # printed if 0: print 0 # NOT printed if 123456789: print 123456789 # printed So unlike what you might expect if element.find(some_string): # WRONG! print "found" else: print "not found" will print "not found" if element starts with some_string and "found" for everything else. As you are not interested in the actual position of the potential substring you should rewrite your code to if "LOCUS" in element: locus += element elif "ACCESSION" in element: accession += element elif "ORGANISM" in element: organism += element which unlike the str.find() method works as expected. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor