停止for循环,只是变为true或false

时间:2014-07-21 01:27:10

标签: python python-2.7

我为我的问题制作了这个示例代码。 我需要离开TrueFalse然后停止循环,但我不知道怎么办?

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

4 个答案:

答案 0 :(得分:5)

您可以使用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循环,else block of the for loop中需要print 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

答案 1 :(得分:2)

虽然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

答案 2 :(得分:-1)

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来提前退出循环。

答案 3 :(得分:-1)

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
            return # or return True depending on how you want it to work
                   # break might also be of value here
        else:
            print False
test()
相关问题