Python for循环在第一个项目之后返回True [英] Python for loop returns True after first item

查看:159
本文介绍了Python for循环在第一个项目之后返回True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

问题:如果a_list中的第一项不是数字,则检查程序将按预期返回False.但是,如果第一个项目是数字,而列表中的任何其他项目都不是,则checker始终返回True.这将导致下一个函数继续处理非数字变量,并导致错误.

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.

如何做到这一点,以便我的函数在返回True之前检查整个列表? 或者,如果需要的话,我该如何创建一个新功能来满足我的需求? 谢谢

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

推荐答案

有一些有用的内置功能全部(和any),用于检查多个条件:

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)

这篇关于Python for循环在第一个项目之后返回True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆