Python: For loop with break

Massimo Scola
Massimo Scola used Ask the Experts™
on
I am new to Python and I am trying to understand the FOR loop.

I am have created a function that searches whether a particular name is in a list. If it is, it should return true.
I understand that break exits the loop .. but why does it not in my case?

def nameSearch(names, target):
    for x in names:
        if x == target:
            return True
            break
        else:
            return False

Open in new window


This is how I call the code:


nameList = ['Smith', 'Jones', 'Turing', 'Bloggs', 'Meyer', 'Hampden']

print()
print('Testing nameSearch()')
print(nameSearch(nameList, 'Turing'))

Open in new window


Even though Turing is in the list, the compiler returns False.

What am I missing?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The error is in the logic.

If the first name is not the one, that you look for you immediately return False

calling return aborts the loop and quits the function call

Even if you searched for the first name in the list you would never hit the break statement as you return alrady in the line before.

There's two ways to solve it.

def nameSearch(names, target):
    for x in names:
        if x == target:
            return True
    # we did not find it in the entire list.
    # so let's return False
    return False

Open in new window


or alternatively if you want to use the break statement and only return at the end of the function:
def nameSearch(names, target):
    result = False
    for x in names:
        if x == target:
            result = True
            break
    return result

Open in new window

Massimo ScolaSoftware Engineer

Author

Commented:
Hi - thanks a lot! It was indeed the logic.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial