Massimo Scola
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?
This is how I call the code:
Even though Turing is in the list, the compiler returns False.
What am I missing?
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
This is how I call the code:
nameList = ['Smith', 'Jones', 'Turing', 'Bloggs', 'Meyer', 'Hampden']
print()
print('Testing nameSearch()')
print(nameSearch(nameList, 'Turing'))
Even though Turing is in the list, the compiler returns False.
What am I missing?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER