1

This code should warn me if an element in the second list is already in the first, after having put the first in lower case.

current_users = ['id_1','id_2','id_3', 'ID_4', 'id_5']
current_users_case = [current_user_case.lower() for current_user_case in current_users]

new_users = ['id_5','id_4','id_7', 'id_8', 'id_9']

for new_user in new_users:
  if new_user == current_user_case:
    print("Sorry, ID already taken")
  else:
    print("ID available")

I get this error message:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from c5n9ss import *
  File "/home/runner/C5py/c5n9ss.py", line 11, in <module>
    if new_user == current_user_case:
NameError: name 'current_user_case' is not defined

But if I test the first two lines in the Python shell, I get the lowered list correctly.

I don't understand the error I get.

RobertCode
  • 17
  • 4

1 Answers1

0

Your idea is good. Just make 2 changes:

  1. Change current_user_case: to current_users_case: (Notice it is users not user in the variable name)
  2. Change if new_user == current_user_case: to if new_user in current_users_case:
current_users = ['id_1','id_2','id_3', 'ID_4', 'id_5']
current_users_case = [current_user_case.lower() for current_user_case in current_users]

new_users = ['id_5','id_4','id_7', 'id_8', 'id_9']

for new_user in new_users:
  if new_user in current_users_case:
    print("Sorry, ID already taken")
  else:
    print("ID available")

When new_user is id_5, you want to compare it to all items in current_users_case. If you compare it to the list, then you won't get a match because string (id_5) is not a list. When you use in, you are checking whether id_5 is in the list and then your code works as expected.

zedfoxus
  • 35,121
  • 5
  • 64
  • 63
  • @2: see: [Check if item is in an array / list](https://stackoverflow.com/questions/11251709/check-if-item-is-in-an-array-list) – Luuk Oct 24 '21 at 17:17
  • Your suggestions work flawlessly. To be honest, I understand the second comment you wrote, but I don't understand the first one. The lines you're referring to seem to be the same both in your code and mine. – RobertCode Nov 11 '21 at 09:55
  • @RobertCode look at your code closely at this line `if new_user == current_user_case:`. The variable on the right side you wrote is current_user_case. It should be current_users_case. Your variable has a missing `s` after user. That's what point `1` is highlighting in my answer. – zedfoxus Nov 11 '21 at 13:28
  • Thanks I understand better what I did wrong. – RobertCode Nov 18 '21 at 10:10