简体   繁体   中英

Function not returning a boolean, returns None always

The following code returns None instead of True , when the input shows that it should clearly return True , what is the error here?

def checkminus(j):
    linp = []
    for a in j:
        if a == '-':
            if len(linp) > 0:
                linp = []
                return False
                quit()
            else:
                linp.append(a)
        else:
            linp.append(a)
    checklen(linp)
def checklen(k):
    l = len(k)
    print(l)
    if l>0:
        return True
    else:
        return False

print(checkminus(['-','5','5','8','2']))

You forgot to return the checklen() return value when you call it:

checklen(linp)

Add a return there:

return checklen(linp)

Note that > already gives you either True or False , so you can just return that directly:

def checklen(k):
    l = len(k)
    return l > 0

Another way of would be to use bool(l) ; lists are False when empty, True otherwise.

Simplifying checkminus() :

def checkminus(j):
    linp = []
    for a in j:
        if a == '-':
            if linp:
                return False
        linp.append(a)
    return bool(linp)

which sounds to me as if you wanted to make sure - is only at the start of the list, or not present at all.

If so, this is easier:

def checkminus(j):
    return len(j) > 0 and '-' not in j[1:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM