Search code examples
pythonloopsfor-loopreturn

python return within loop


If I define:

def hasNoX_2(s):
    if type(s)!=str:
       return False
    for c in s:
        if c!='x' or c!='X':
           return True
    return False

and enter hasNoX_2('Xenon'), True is returned and I'm not sure why. Nothing is being returned in the first If statement, since it only returns False if s is NOT a string. So what is the for loop "looking" at when it says, "Hey, I don't see 'x' or 'X', so I can return True?"


Solution

  • Let's focus just on the if statement

    if c!='x' or c!='X':
    

    This is a boolean expression with two terms

    • c != 'x' and
    • c != 'X'

    As you use the or operator, if either term evaluates as True, then the entire expression evaluates as True. If the expression evaluates as True, then the body of the if statement (in this case return True) is executed.

    Here is the standard truth table for an or expression (A or B)

     A or B     | A = False | A = True |
     ----------------------------------
    | B = False | False     | True     |
    | B = True  | True      | True     |
    

    As you can see, the result is False only if both terms are False

    Let's look at how your expression evaluates for each type of input

    c                   | c != 'x' | c != 'X' | or expression |
    ----------------------------------------------------------
    'x'                 | False    | True     | True          |
    'X'                 | True     | False    | True          |
    any other character | True     | True     | True          |
    

    In short, your expression will always evaluate as True - and the if branch will always be taken.

    So, the function will return True when it examines the first character in the provided string.

    The only ways this function can return False are

    • If something other than a str is provided
    • If an empty string is provided - because the for loop is never entered.