[Tutor] if >= 0

ALAN GAULD alan.gauld at btinternet.com
Tue Feb 11 10:31:26 CET 2014


CCing the list. Please use Reply All when responding.

> thanks Alan, i understand now zero is False. 

That's right. but...

> so if one of the 'if' test is false, that 'for' loop is also halted? 
> and does not proceed to the next element?

This bit  is wrong.


The for loop will continue to completion every time.


>>> for element in in_file:
>>>   if  element.find(LOCUS'):

>>>     locus += element
>>>   elif element.find(...)

What happens is that because the find(LOCUS) is the first test it will almost 
always be true. So the locus += element will be executed on almost every line
Because that branch of the if construct is executed no other branch is executed.

In an if/elif/else structure only one branch ever gets executed in a given 
iteration of the for loop. elif stands for "else if" so the test in the elif statements 
only get executed if all the preceding tests fail. So the order of the tests is 
very important. Now in your case the first branch nearly always succeeds  
and so the subsequent branches never get executed. 

When you add the >=0 condition you stop the first test from catching everything.

So the lines that do not contain LOCUS now get tested for the other values 
and as a result update their respective string variables.

But the for loop continues regardless of which branch is used, it is only 
controlled by the number of lines in the file. It does not care what the code 
inside the loop body does (unless it explicitly uses return or break or continue).

HTH

Alan g. 


More information about the Tutor mailing list