I am new to this and wonder what I have missed or have done wrong.
It seems that the code only works if individual items from the list are selected but fails with the whole list.
Thank you for your help!
current_users = ['barry', 'eric', 'wendy', 'anne', 'nigel']
new_users = ['jane', 'alan', 'WENDY', 'NIGEL', 'john']
#convert new_users to lower case and name new_users1
new_users1 = [x.lower() for x in new_users]
print (new_users1) #show that new users1 is valid
for x in new_users1:
#if user names do not clash then ok otherwise try a new user name
if x in new_users1 in current_users: #this line does not seem to execute when presented with the full new_users1 but does when individual users are selected []
print (x.title()," You will need to enter a new user name")
if x in new_users1 not in current_users:
print (x.title()," Your chosen user name is available")
#this should work
# if x in new_users1 [2] in current_users:
# print(x.title(), " You will need to enter a new user name")
# if x in new_users1 [1] not in current_users:
# print (x.title()," Your chosen user name is available")
What do you expect this piece of code to do? It is used as an if condition, so it should result in a False/True result. Write out when you want it to be true and when you want it to be false.
Python supports “chained” comparisons. That means that, say, a <= b <= c is equivalent to a <= b and b <= c, and a == b == c is equivalent to a == b and b == c, except that b is evaluated only once on both cases.
Comparisons include in and not in, so x in new_users1 in current_users is equivalent to x in new_users1 and new_users1 in current_users.
That might be useful if you’re testing whether an item is in a list which is also in another list, or something similar, but that’s something you rarely want to do.
It iterates over items in new_users1. You want to know whether this item (name) is in current_users then you should write:
if x in current_users:
# do something
Meaningful names are important, it makes code more readable and easier to understand:
current_users = ['barry', 'eric', 'wendy', 'anne', 'nigel']
new_users = ['jane', 'alan', 'WENDY', 'NIGEL', 'john']
new_users_1 = [name.lower() for name in new_users]
for name in new_users_1:
if name in current_users:
print(f"{name.title()}, You will need to enter a new user name")
else:
print(f"{name.title()}, Your chosen user name is available")
# Prints:
# Jane, Your chosen user name is available
# Alan, Your chosen user name is available
# Wendy, You will need to enter a new user name
# Nigel, You will need to enter a new user name
# John, Your chosen user name is available