简体   繁体   中英

Python for loop returns True after first item

def checker(a_list):
    for item in a_list:
        if str(item).isdigit():
            return True
        else:
            return False

The variable I have for checker is a list of four string containing variables. I planned to use it as a 'checker' to see if all input values of another function contained only digits.

Problem: If the first item in a_list is not a number, checker returns False as it should. However, if the first item is a number while any others in the list aren't, checker returns True anyways. This causes the next function to proceed with the non-number variables and results in an error.

How do I make it so my function checks the entire list before returning True? Or if need be, how do I make a new function that does what I'm looking for? Thanks

Don't return True in the loop. In the loop return False if an item is NOT a digit . Move return True after the loop has completed.

def checker(a_list):
    for item in a_list:
        if not str(item).isdigit():
            return False
    return True

There are usefull built-in fuctions all (and any ) for checking multiple conditions:

def checker(a_list):
    return all(str(item).isdigit() for item in a_list)

I'm assuming you want to check that all elements of a_list return True as a return value from isdigit() .

In this case, use the built-in function all

all(str(s).isdigit() for s in a_list)

for more information on any and all , check out this link on SO: any and all explained

edit: thanks @RoadRunner for pointing out conversion to str as OP had it in it's example he gave.

This should check if all items in the list are digits

if all(str(x).isdigit() for x in a_list):
    return True
else:
    return False

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