停止for循环,得到true或false

2024-06-16 16:17:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我为我的问题编写了这个示例代码。 我需要出去True或者False然后停止循环,但我不知道怎么做?你知道吗

def test():
    list = [u"sam", u"jay", u"jean", u"smo", u"gon", u"bil"]
    user = u"jean"
    for x in list:
        if user==x:
            print True
        else:
            print False
test()

输出:

False
False
True
False
False
False

Tags: 代码testfalsetrue示例samdefjean
3条回答

您可以使用in

def test():
    users = [u"sam", u"jay", u"jean", u"smo", u"gon", u"bil"]
    user = u"jean"
    return user in users

演示:

>>> users = [u"sam", u"jay", u"jean", u"smo", u"gon", u"bil"]
>>> user = u"jean"
>>> user in users
True

请注意,list不是一个好的变量名,因为它隐藏了内置的list。你知道吗


如果您需要一个for循环,则需要在匹配时break循环,并在^{} block of the ^{} loopprint False

def test():
    users = [u"sam", u"jay", u"jean", u"smo", u"gon", u"bil"]
    user = u"jean"
    for x in users:
        if user == x:
            print True
            break
    else:
        print False

虽然alecxe有最好的答案,但还有一个选择:变量!你知道吗

def test():
    users = [u"sam", u"jay", u"jean", u"smo", u"gon", u"bil"]
    user = u"jean"

    found = False
    for x in users:
        if user == x:
            found = True;

    print found
def test():
    list = [u"sam", u"jay", u"jean", u"smo", u"gon", u"bil"]
    user = u"jean"
    for x in list:
        if user==x:
            print True
            break
        else:
            print False
test()

可以使用break提前退出循环。你知道吗

相关问题 更多 >