Link to home
Start Free TrialLog in
Avatar of Massimo Scola
Massimo ScolaFlag for Switzerland

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Massimo Scola

ASKER

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