Reputation: 11
The function I call from the main program is
elif retrieve_user(user_login):
print("Hello " + user_login + ", welcome!\n")
I use the function util.csv_to_dict('user.csv')
and I want to find the name of users they inclound in user.csv file:
news_items = util.csv_to_dict('users.csv')
print("The list of contacts ie: \n", news_items)
for n in news_items:
if n==username:
print('O user found!!!!')
return True
else:
return False
Its not work and I don't know the reason. Pls help.
Upvotes: 1
Views: 78
Reputation: 56
I notice that you are utilizing dictionary in your code. Normally when dealing with dictionaries, I use exception handling to "increase efficiency" of my code. "Better to ask forgiveness than permission"
Alternative solution:
def check_user(username):
news_items = util.csv_to_dict('users.csv')
print("The list of contacts ie: \n", news_items)
try:
if news_items[username]:
print('O user found!!!!')
return True
except:
return False
Upvotes: 1
Reputation: 1251
I think your code should look more like:
news_items = util.csv_to_dict('users.csv')
print("The list of contacts ie: \n", news_items)
for n in news_items:
if n==username:
print('O user found!!!!')
return True
return False
That way, it's only after looping on all keys, if the user wasn't found you return False
value. In your original code, only the first iteration of the for
loop is completed and you will return value True
only if it matches the first one.
Don't hesitate if you need more explanations.
Upvotes: 1