Avatar of Massimo Scola
Massimo Scola
Flag 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?
Python

Avatar of undefined
Last Comment
Massimo Scola

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
gelonida

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Massimo Scola

ASKER
Hi - thanks a lot! It was indeed the logic.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck