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()