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 li
Solution 1:
There are usefull built-in fuctions all (and any
) for checking multiple conditions:
defchecker(a_list):
returnall(str(item).isdigit() for item in a_list)
Solution 2:
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.
defchecker(a_list):
for item in a_list:
ifnotstr(item).isdigit():
returnFalsereturnTrue
Solution 3:
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.
Solution 4:
This should check if all items in the list are digits
ifall(str(x).isdigit() for x in a_list):
returnTrueelse:
returnFalse
Post a Comment for "Python For Loop Returns True After First Item"