Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I search a SQL List inside of python to check if the username matches a user input?

So I am making a login page, and I need to compare the username of an SQL list to the user input. I will also use the answer for the password. This is what I have tried and it returns false.

list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')]

for i in list_of_users:
    if i == 'joe@gmail.com':
        print("True")
    else:
        print("False")

The list_of_users is there to simulate what the SQL gives when you do cursor.fetchall() on an SQL database.
Any input would be appriciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because the elements of your list are tuples of two elements. So each element has two in turn. See the definition in the official documentation of Data Structures – Tuples and Sequences.

If you wanted to fix your code, you would then simply add a second element to the for loop:

list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')]

for email, pwd in list_of_users:
    if email == 'joe@gmail.com':
        print("True")
    else:
        print("False")

But this approach has a fundamental flaw for your use case. You want to print N times ‘false’? Just iterate until the mail is found and stop.

This is an example toy code:

list_of_users = [('joe@gmail.com', 'qwerty'), ('jeremy', '123')]


def login(email: str, pwd: str, list_of_users: [()]) -> bool:
    for db_email, db_pwd in list_of_users:
         if (email == db_email) and (pwd == db_pwd):
             return True
    return False


print(login('jeremy', '123', list_of_users))  # True
print(login('jeremy', '456', list_of_users))  # False
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading