Zack
Zack

Reputation: 671

Unsure of for loop

Not sure what I'm doing wrong here. Any help would be appreciated. When I enter a DNA sequence that contains a bad variable (like Z) I keep getting a return True. Can someone point out why?

Thanks

def is_valid_sequence(dna):
    """ (str) -> bool

    >>> is_valid_sequence('ATCG')
    True
    >>> is_valid_sequence('AZT')
    False
    >>> is_valid_sequence('atcg')
    False

    Returns a boolean result based on whether dna is a valid
    dna sequence.
    """



    for char in dna:
        if char in "TCGA":
            return True
        else:
            return False

Upvotes: 0

Views: 114

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308121

You're always returning after testing the first character. Keep testing until you reach a bad character, don't return True until you've tested the whole string.

Upvotes: 1

arshajii
arshajii

Reputation: 129497

You're returning on the first iteration of the loop: return ends the function, and all paths in the body of your loop contain a return. You probably want

for char in dna:
    if char not in 'TCGA':
        return False
return True

Or, more Pythonically:

return all(char in 'TCGA' for char in dna)

Upvotes: 7

Ankur Ankan
Ankur Ankan

Reputation: 3066

In your code you take char one by one and return True if it is in "TCGA". So if the first char is in "TCGA" it would return True and will stop execution. You should do something like this:

for char in dna:
    if char not in "TCGA":
        return False

Upvotes: 1

Related Questions