[Tutor] GC content: Help with if/else statements:

Alan Gauld alan.gauld at btinternet.com
Sun Oct 13 09:38:43 EDT 2019


On 13/10/2019 06:17, Mihir Kharate wrote:

>     if character == 'A' or 'T' or 'G' or 'C':

Python doesn't see this the way you do.
It sees

if (character == 'A') or
   ('T' == true) or
   ('G' == True) or
   ('C' == True):

And it evaluates it from the leftmost expression, so first t checks if
character is 'A'. If not it then tests if 'T' is True. Now in python any
non-empty string is considered to be True, so it sees the second test as
True.

Now in an or expression Python stops evaluating conditions
when it finds a True expression. Thus it never evaluates the
last two expression(although they would always be True too)
and interprets the whole if expression as True and so never
enters the else clause.

You could change the code to

if character == 'A' or character == 'T'
   or character == 'G' or character == 'C':

But, as Joel has already pointed out a more Pythonic option
in this case is to use the in operator:

if character in ('A','T','G','C'):



> *Question 2*: When I use another if statement like below, it returns the GC
> content and "Invalid base-pair in your Sequence" both. No matter whether
> the input has any other characters than A,T,G,C or not.
> 
>     if character == 'A' or 'T' or 'G' or 'C':
>         print ("The GC content is: " + str(gc_cont) + " %")
>     if character is not 'A' or 'T' or 'G' or 'C':

Same problem again. Python sees this as

if (character is not 'A') or ('T' == True)....

With the same result as before. The fix is similar:

if character not in ('A','T','G','C')...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list