user2100672
user2100672

Reputation:

Using conditions with CSV rows

I'm looking at creating a very basic username and password program using an external CSV file. The program allows the user to input a username and password, afterwards an if statement checks whether the username and password match that of a row in the CSV document. If so then the corresponding user information is displayed.

The issue I'm having is to with my else: statement. If the user details don't match that of a row (wrong username or password) a notification should display. By adding an else line though, it checks per line so I receive more than one "Details entered incorrectly." messages. Also if the credentials are correct, the user information is displayed alongside "Details entered incorrectly" for every other row.

import csv

Username = input("Username: ")
Password = input("Password: ")

with open('data.csv', 'rt', newline='') as file:

    open_file = csv.reader(file)

for row in open_file:
    if row[0] == Username and row[1] == Password:
        print("Secret phrase: ", row[2])
    else:
        print("Incorrect user details.")

Any ideas on how I could alter my code to fix this? Much appreciated!

Upvotes: 0

Views: 74

Answers (1)

Noctua
Noctua

Reputation: 5208

There's something lovely in python, called the for-else. This else clause, belonging to a for-loop instead of an if, is executed if the loops exits normally (the iterator runs out):

for row in open_file:
    if row[0] == Username and row[1] == Password:
        print("Secret phrase: ", row[2])
        break # stop searching and skip the for-else.
else:
    print("Incorrect user details.")

I don't quite understand what you mean with

Also if the credentials are correct, the user information is displayed alongside "Details entered incorrectly" for every other row. Could you elaborate or give an example?

Upvotes: 3

Related Questions