Reputation: 23
I'm new to python and i got a problem with my code.. so what I'm trying to do is to ask some random name and that program should tell you if a name is in the list
names = ["Demi", "Siru", "Datte", "Sony", "Jami", "Windy", "Paavo", "Roosa"]
x = input('Give a name: ')
for y in names:
if(x==y):
print( x + " is in a list" )
break
elif(y!=x):
print("it's not in a list")
break
Upvotes: 1
Views: 43
Reputation: 2169
names = ['ed', 'edd', 'eddy']
found = False
end = False
while(end != True):
user_input = input('enter name... ')
for name in names:
if name == user_input:
found = True
if found:
print('yep! the name {} is available'.format(name))
else:
print('hold up! wait a minute! no name found!')
again = input('continue? [y/n] ? ')
if again == 'n':
end = True
else:
found = False
Upvotes: 0
Reputation: 6426
You're iterating through the list, making a comparison, then break
ing out of the loop as soon as you've processed the first item. Remove break
.
That aside, the solution to your problem is to use if item in my_list:
instead of that for
loop nonsense.
Alternatively, you could use for: else:
like so:
for y in names:
if x == y:
print("yes it is in there")
break
else:
print("no it is not")
You'll see that else:
is attached to the for
loop itself, as opposed to the if
. The else
is checking to see whether there was no break
. Break causes the loop to exit early.
Upvotes: 0
Reputation: 19342
The correct code would go through all the items in the list, and if one matches break out of it, but only if none of them matched, conclude that it is not found (so that part goes out of the loop), like this:
for y in names:
if x == y:
print("{} is in the list".format(x))
break
else:
print("it's not in the list")
Of course, it can be done without the loop completely:
if x in names:
print("{} is in the list".format(x))
else:
print("it's not in the list")
Upvotes: 3
Reputation: 420
Use List Comprehension.
x +"In List" if x in names else "Not in List"
Upvotes: -1
Reputation: 25181
Because you check only the first item of the list and then break.
Try to remove the break
.
Upvotes: 0