kile
kile

Reputation: 141

Return in a for loop function

What's wrong with this? Why is this always True no matter what I input?

def duplicates(s):
    for c in s:
        if s.count(c) > 1:
            
            return False
            
        else:
            return True

print(duplicates("god"))
print(duplicates("goo"))
print(duplicates("good"))

Upvotes: 0

Views: 72

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

The loop body never executes more than once, since no matter what, you are executing a return of either True or False on the very first iteration.

To fix it, only return False from within the loop. Don't return True until after the loop exits:

def duplicates(s):
    for c in s:
        if s.count(c) > 1:
            return False

    return True

The function name is a little misleading, since it returns True if there are no duplicates and False if there are duplicates.

Upvotes: 2

Related Questions