Python 停止for循环,得到true或false

Python 停止for循环,得到true或false,python,python-2.7,Python,Python 2.7,我为我的问题编写了这个示例代码。 我只需要退出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() 输出

我为我的问题编写了这个示例代码。 我只需要退出
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

您只需在中使用

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

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


如果你需要一个
循环,你需要
打破循环,当你点击一个匹配项时,在以下位置
打印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

您可以使用break提前退出循环。

不,我应该在代码中使用for循环。这只是我的问题的一个例子。我需要循环的
解决方案
我尝试将
中断
但输出打印
然后打印
,但我需要在找到正确的值时打印
并停止。@yuyb0y确保运行与答案中相同的代码-我在发布之前已经测试过它。而这如果用法正确,我发现
else
的Python语法与
for
while
循环特别不直观。我希望他们用另一个关键字来代替。@PeterGibson是的,这不是一种流行的编程技术,但在工具箱中使用它是很好的。请注意,这将打印
“False False True”
。我认为这比使用带有循环的
else
语句更清楚谢谢。这对我来说是新的。请注意,这将打印出
“False False True”
,它与will在您之前3小时的回答完全相同。对不起。打开的时候很忙,有一段时间没有发送。
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()
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()
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()