Python for loop returns True after first item

倾然丶 夕夏残阳落幕 提交于 2020-01-22 02:42:09

问题


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


回答1:


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)



回答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.

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



回答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.




回答4:


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


来源:https://stackoverflow.com/questions/48040762/python-for-loop-returns-true-after-first-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!