-1

I make this example code for my problem. I need to get out just True or False and stop the loop but i dont know how?

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

The output:

False
False
True
False
False
False
yuyb0y
  • 105
  • 1
  • 2
  • 6

4 Answers4

5

You can just use in:

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

Demo:

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

Note that list is not a good variable name since it shadows built-in list.


In case you need a for loop, you need to break the loop when you hit a match and print False in the else block of the for loop:

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
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • no i should use for loop in my code. this is just example for my problem.i need solution for `for loop` – yuyb0y Jul 21 '14 at 01:30
  • I try to put `break` but the output print `True` then print `False` but i need when find the correct value print `True` and stop. – yuyb0y Jul 21 '14 at 01:37
  • @yuyb0y make sure you run the same code as in the answer - I've tested it before posting. – alecxe Jul 21 '14 at 01:38
  • While this is the correct usage, I find the Python syntax for `else` with `for` and `while` loops particularly unintuitive. I wish they had used another keyword instead. – Peter Gibson Jul 21 '14 at 01:56
  • @PeterGibson yeah, it is not a popular programming technique, but it is good to have it in a toolkit. – alecxe Jul 21 '14 at 02:00
2

While alecxe has the best answer, there's one more option: variables!

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
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
-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()

You can use break to exit a loop prematurely.

Will
  • 5
  • 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()
BWStearns
  • 2,567
  • 2
  • 19
  • 33