Ends-with and Starts-with in if statements: Python 3

user3230395 picture user3230395 · Jan 24, 2014 · Viewed 12.5k times · Source

I am new to python and I have to create a program that validates a DNA sequence. (background on DNA sequences really quick) in order to be valid: • The number of characters is divisible by 3 • The first 3 characters are ATG • The last 3 characters are TAA, TAG, or TGA.

my problem comes in with using Boolean terms in an if statement.

        endswith=(DNA.endswith("TAA"))
endswith2=(DNA.endswith("TAG"))
endswith3=(DNA.endswith("TGA"))
if length%3==0 and startswith==true and endswith==true or endswith2==true or endswith3==true:
    return ("true")

this code returns the error of: global name 'true' is not defined

How do I fix this, and also just on a last note I am really sorry. The answer to this question is probably SO stupidly simple that in your mind a 2 year old could code it :/ I did research around but I had no luck at all. So I thank you for taking your time to even read my stupid question.

Answer

Tim Peters picture Tim Peters · Jan 24, 2014

Much easier:

return (len(DNA) % 3 == 0 and
        DNA.startswith("ATG") and
        DNA.endswith(("TAA", "TAG", "TGA")))

Comparing a boolean value to True or False is almost always redundant, so whenever you find yourself doing that ... do something else ;-)