Title: CSV-based login system issues
Tags: python;csv
Question: My CSV login system exits when the user attempts to log in, even if the details are correct. It crashes with no warnings or errors.
I'm using Python 3.7.3 on Windows 10.
I've tried making the for loop a for-else loop, I've also tried reading the CSV file as a text file in the past.
attempt = 0
def main():
global attempt
with open('details.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
row_count = len(csv_file.readlines()) - 1
print("Welcome to Dice Game! There are {0} currently registered users.".format(row_count))
print("=====================================================================\n")
username = input("Enter Username: ").lower()
password = input("Enter Password: ")
for row in csv_reader:
if username == row["username"].lower() and password == row["password"]:
print("\nLogged in as {0}.\n".format(username.capitalize()))
game()
else:
attempt += 1
print("\nInvalid login! (Attempt {0})\n".format(attempt))
if attempt == 3:
print("\nLocked Out!")
else:
main()
I expect it to take the user to the next section (in this case a function called game) or if the login is incorrect, warn the user.
Comment: print(row) doesn't output anything.

Comment: So does it at least print the `"Logged in as ..."` line or not? Have you tried placing some kind of `print(row)` above the `if username == row[...` line, so you can see what is actually being compared to what?

Comment: You never say what exactly is not working with the code you have. Please [edit] your question and fix that.

Here is the accepted answer: It looks your indentation is messed up, which is important in python. If you have two blank lines between getting the creds and looping, that will exit main().
Otherwise, I would do it this way:
with open('details.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
max_attempts = 3
for attempt in range(1:max_attempts + 1):
username = input("Enter Username: ").lower()
password = input("Enter Password: ")
if any(row["username"].lower() and password == row["password"] for row in csv_reader):
print("\nLogged in as {0}.\n".format(username.capitalize()))
game()
else:
print("\nInvalid login! (Attempt {0})\n".format(attempt))
if attempt == 3:
print("\nLocked Out!")


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:05/16/19', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><csv>', 'Title': 'CSV-based login system issues', 'ViewCount': 72, 'id': 56173566, 'user_AboutMe': None, 'user_AccountId': 15952249.0, 'user_DisplayName': 'iCrazyBlaze', 'user_Reputation': 3.0, 'user_Views': 4.0, 'user_id': 11511288.0}}