Skip to content
Advertisement

Why isn’t my for loop working for my expression?

I want this function to read a password, and check to see if it has at least 1 number in it. If not, it needs to return False. I need to use a for loop with the range function and this is what I have:

def hasNum(password):
for i in range(0,len(password),1):
    if password == str('0123456789'):
        return True
    else:
        return False

I’ve tried different variations and it’s driving me crazy. Can someone possibly explain to a rookie what they’re doing wrong?

Advertisement

Answer

The loop tests once if the password is 0123456789; if it matches that string, True is returned, otherwise False is returned outright. The range(0, len(password), 1) is a complicated way to write range(len(password)); likewise str('0123456789') is a complicated way of writing '0123456789'.

What you need is to iterate over each character, and if it is a digit, then return True; if none is, then return False:

def has_digit(password):
    for character in password:
        if character.isdigit():
            return True

    return False

The final return False is outside the loop – we must check each and every character in the password before returning False.

This can be simplified with any:

def has_digit(password):
    return any(ch.isdigit() for ch in password)
Advertisement