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

Alan Gauld alan.gauld at btinternet.com
Sun Oct 13 14:10:18 EDT 2019


On 13/10/2019 16:52, Mihir Kharate wrote:
> @Joel Goldstick , I tried what you suggested. Its still returning the first
> if statement. If I input a sequence which has a different letter than
> A/T/G/C (for example, if I input ATFGC as my input when prompted) , it does
> not return the error message: "Invalid base-pair in your Sequence".

First a point about terminology, which is important in programming.
Your function des not *return* anything it prints its output. Returning
something means you use thereturn statement to pass back a value to the
caller. You are not doing that.

Now to your point.
You say you took Joel's advive which means, I assume,
that your function now looks like:

def gc_content():
    global a,t,g,c
    for character in input_sequence:
        if character == 'G':
            g+=1
        if character == 'C':
            c+=1
        if character == 'T':
            t+=1
        if character == 'A':
            a+=1
        gc_cont = (g+c)/(a+g+t+c)*100
    if character in ('A',  'T', 'G', 'C'):
        print ("The GC content is: " + str(gc_cont) + " %")
    else :
        print("Invalid base-pair in your Sequence")

If so the if test only looks at the last character because it
is outside the for loop. If you want the if test to apply to all the
characters then you need to put it inside the functon.
Like this:

def gc_content():
    global a,t,g,c
    for character in input_sequence:
        if character == 'G':
            g+=1
        if character == 'C':
            c+=1
        if character == 'T':
            t+=1
        if character == 'A':
            a+=1
        gc_cont = (g+c)/(a+g+t+c)*100
        if character in ('A',  'T', 'G', 'C'):
            print ("The GC content is: " + str(gc_cont) + " %")
        else :
            print("Invalid base-pair in your Sequence")

That will do what I think you want.

-- 
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