beckevans
beckevans

Reputation: 11

Why is it printing both 'username found' and 'username not found'?

database=[['username1','password1'],['username2','password2']]

def get_username():
  username= input('enter username:')
  return username

def check_username():
  username=get_username() 
  for pair in database:
    if username==pair[0]:
      print('username found!')
    else:
      print('username not found.')

ouput:

enter username: username1
       username found!
       username not found.

Upvotes: 0

Views: 89

Answers (4)

Buddy Bob
Buddy Bob

Reputation: 5889

Currently what is happening in your code is, you iterate through your pairs correctly (bad indentation) and you check if user input is in a pair. If not it will print not found. Then it will move onto the second pair. If your username is found in that pair, you will receive found. So your output is ugly.

not found
found

Instead, I suggest, fixing your indentation. Iterate through your pairs, check if your username meets in any of the pairs. If I cannot find a match in any pair then I execute else which is waiting outside our for loop #Note: else is not needed, but for clarification, I will keep it there. But say we find the username in a pair, you execute the if and break out of the for loop.

database=[['username1','password1'],['username2','password2']]

def get_username():
  username= input('enter username:')
  return username

def check_username():
    username=get_username() 
    for pair in database:
        if username==pair[0]:
            return 'username found!'
    return 'username not found.'
print(check_username())

Upvotes: 1

Franco Morero
Franco Morero

Reputation: 559

It is because you are printing inside a for a loop. The python doc has a great example of how it works.

If you print pair inside check_username like this:

def check_username():
    username=get_username() 
    for pair in database:
        print(pair)

You will get:

['username1', 'password1']
['username2', 'password2']

So in the first list, your variable username will be equal to pair[0], so the username found! will be print, but in the second list the variable username is different to pair[0], so username not found will be print.

To fix this, the way to go in python is using a for/else block, like this:

def check_username():
    username=get_username() 
    for pair in database:
        if username==pair[0]:
            print('username found!')
            break
    else:
        print('username not found.')

Upvotes: 1

Fardin Ahsan
Fardin Ahsan

Reputation: 53

You need to exit out of your loop once the username is found. So include a break clause inside of your first conditional statement.

Upvotes: 0

Silver
Silver

Reputation: 406

This code might help.

def check_username():
  username=get_username() 
  for pair in database:
    if username==pair[0]:
      print('username found!')
      return
  print('username not found.')
  return

Upvotes: 1

Related Questions