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 ScolaInternshipAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Massimo ScolaInternshipAuthor Commented:
Hi - thanks a lot! It was indeed the logic.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.