-1

I want to make a code that to see if each new username has already been used in a website.

I have this code:

current_users = ['Rachel', 'Ross', 'Chandler', 'Joey', 'Monica']

new_users = ['Janice', 'Ben', 'Phoebe', 'JOEY']

for new_user in new_users:
    if new_user in current_users:
    print (f'The username {new_user} is alreay in use. You need to enter a new username')

else:
    print (f'The username {new_user} is avaliable')

And this outputs:

  • The username Janice is avaliable
  • The username Ben is avaliable
  • The username Phoebe is avaliable
  • The username JOEY is avaliable

For "JOEY" the message to be printed was supposed to be this: "The username JOEY is alreay in use. You need to enter a new username".

How can I lowercase (or uppercase) the lists to make this code case-insensitive?

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
DR8
  • 127
  • 5
  • 2
    The simplest solution would be to lowercase all the values in `current_users` then use `if new_user.lower() in current_users` – Nick Jun 11 '22 at 23:53
  • 1
    @AsishM. Not really, because creating a list with all of the lowercased names isn't the best approach for this particular case. See my answer for more details. – BrokenBenchmark Jun 11 '22 at 23:57

1 Answers1

2

You should create a set that contains all of the lowercased names. Then, to check whether a name can be used, look up the lowercased version of the name in the set:

names_in_use = {name.lower() for name in current_users}

for new_user in new_users:
    if new_user.lower() in names_in_use:
        print (f'The username {new_user} is already in use. You need to enter a new username')
    else:
        print (f'The username {new_user} is avaliable')

This outputs:

The username Janice is avaliable
The username Ben is avaliable
The username Phoebe is avaliable
The username JOEY is already in use. You need to enter a new username
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33