Python: For loop with break

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?
Massimo ScolaAsked:
Who is Participating?
 
gelonidaCommented:
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

0
 
Massimo ScolaAuthor Commented:
Hi - thanks a lot! It was indeed the logic.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.