Skip to content Skip to sidebar Skip to footer

Specific Indentation Error In Nested If Statement In For Loop

I have the following code and in the login feature, the output is erroneous (a logic error). It basically prints 'invalid username and password' until it gets to the right one, and

Solution 1:

You can leverage exceptions to write login this way.

def login():
  print("*****LOGIN SCREEN******")
  username=input("Username: ")
  password=input("Password: ")
  try:
    index = usernames.index(username)
    if password == passwords[index]:
      print("correct login")
    else:
      print("invalid username or password")
  except:
    print("invalid username or password")

Solution 2:

You're seeing this happen because of the else statement in your login function. Basically what your code is currently doing in that function is looping through, checking to see if the username and password are equal to the current value (i.e. compare user1 == user2) if they do not equal then you automatically print the invalid user name.

Instead you should wait until you compare all of the values to print the invalid username or password message. Also - instead of continuing to loop through your values, you could add a break to stop the for loop once the valid value is found. Your login function would look something like this:

def login():
  print("*****LOGIN SCREEN******")
  username=input("Username: ")
  password=input("Password: ")
  found = False
  for index_of_current_user, current_user in enumerate(usernames): #enumerate allows to you to go throw the list and gives to you the current element, and the index of the current element
    if username == current_user and passwords[index_of_current_user] == password: #since the two list are linked, you can use the index of the user to get the password in the passwords list
      print("correct login")
      found = True
      break
  if found == False:
    print("invalid username or password")

That will give you only 1 instance of either correct login or invalid username or password.


Solution 3:

In your login() function, you print for every element of the list, so you could print after the loop doing:

def login():
  print("*****LOGIN SCREEN******")
  username=input("Username: ")
  password=input("Password: ")
  correct_login = False
  for index_of_current_user, current_user in enumerate(usernames): #enumerate allows to you to go throw the list and gives to you the current element, and the index of the current element
    if username == current_user and passwords[index_of_current_user] == password: #since the two list are linked, you can use the index of the user to get the password in the passwords list
      correct_login = True
      break
  if(correct_login):
    print("correct login")
  else:
    print("invalid user name or password")

Post a Comment for "Specific Indentation Error In Nested If Statement In For Loop"