I want to create a simple log-in account program in Python using the "CSV" library. Here is the code:
import csv
account_password = ""
with open("accounts.csv") as csvfile:
reader = csv.reader(csvfile)
while True:
username = input("\nEnter username: ")
# Checks if username exists
for row in reader:
if row[0] == username:
account_password = row[1] # Get user's password
break
password = input("Enter password: ")
# Check if password is valid
if password == account_password:
break
else:
print("Username/password is incorrect. Try again.")
print("\nSuccessfully logged in!")
Here is how my CSV file looks like. The first column is the usernames and the second one is the passwords:
Tim,myPassword
John,monkey32
Fred,WooHoo!
When I tried to test my program in IDLE, I noticed an unusual log-in issue.
If I log in with the correct credentials, then the program works perfectly fine:
If I log in with incorrect log in details, the program works as expected:
But here is the issue. After entering incorrect log in details, the program asks the user to try again. This is done with a "while loop" in my code. Yet when I "try again", but with the correct details, the program thinks the log-in details are incorrect:
Here is the same issue with another user from the csv file:
I would love it if anyone could let me know what is wrong with my code.
Please also show the full updated code along with an explanation for why the code in the answer is working and the difference between it and mine.
Thank you.