Search code examples
pythonfor-loopcomparison-operators

Python : How to check if input is not equal to any item in a 2d array?


I was trying to check if the username entered is equal to the second index of item in the list, and I tried to use !=, but it still keeps letting the same username to be registered. What's the problem with the code ?

Registering username :

user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]

name = input("Please enter your name : ")
while True:
     if name == '':
          name = input("Please enter your name : ")
     else:
          for user in user_list:
               if name != user[1]:
                    break # break out for loop
          else:
               print("This username has been registered")
               name = input("Please try another username : ") 
               continue # continue the while loop
          break # break out while loop
print("Username registered as",name)

Editted:

The results of != and == seems to be different, the == works.

Login username :

user_list = [['std1','Daniel'],['std2','Raymond'],['std3','Emanuel']]

name = input("Please enter your name : ")
while True:
     if name == '':
          name = input("Please enter your name : ")
     else:
          for user in user_list:
               if name == user[1]:
                    break # break out for loop
          else:
               print("Unregistered username")
               name = input("Please try another username : ") 
               continue # continue the while loop
          break # break out while loop
print("Logged in as",name)

Solution

  • You're very close!
    What you're trying to do: break out of the loop if there are any names in user_list that match the new name.
    What it's currently doing: breaking out of the loop if there are any names in user_list that don't match the new name.
    I.e., if you enter Daniel, since Daniel != Raymond, you will break early.

    Instead, what you should do is break if the newly entered name is not present in a list of names:

    user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
    
    name = input("Please enter your name : ")
    while True:
        if name == '':
             name = input("Please enter your name : ")
        else:
            if name in [user[1] for user in user_list]:  # existing names list
                print("This username has been registered")
                name = input("Please try another username : ")
            else:
                break
    print("Username registered as",name)