0

I'm creating a login and menu program and I have a CSV file with the login and passwords from some users I have invented. When I run the program, it does without any errors, but when I introduce a right username and password, It doesn't work properly.

My code prints "Access not granted" when it should print "Access granted".

This is how my CSV looks when I print it in the console:

[['Username' 'Password' 'Access Level'] ['booker12' '12se74' '1'] ['grey07' '04ap67' '1'] ['johnson81' '30no86' '1'] ['jenkins46' '14ju73' '1'] ['smith79' '09ja61' '1'] ['ccastrej' 'superuser03' '3'] ['ssofia' 'semigod1' '2'] ['isabella' 'payasian' '2'] ['pablitohesk' 'soccer13' '2'] ['teacher' 'igradethis100' '3'] ['pedrocorte' 'asturiano' '1'] ['andrea' 'jesusito' '1']]

Here is the code I have right now:

import sys
import csv
import numpy as np

def Main():
    login()

def login():
    with open('MatrixAccess.csv') as csvfile: #I import the csv file
        reader = csv.reader(csvfile, delimiter = ';') #I read through it
        x = list(reader) # I convert the csv into an array to loop through it easier with the numpy library
    print(np.matrix(x)) #I print it to check if I imported it correctly
    print("Username: ")
    str1 = input()
    print("Password: ")
    str2 = input()
    for i in [2]:
            for j in [i]: #I have to convert the ints to lists so I can iterate through the list
                if(str1 == x[i][j] and str2 == x[i][j+1]):
                    print("Access granted")
                else:
                    print("Access not granted")

def menu():
    print("************MAIN MENU**************")
Barmar
  • 741,623
  • 53
  • 500
  • 612
solrakcs
  • 49
  • 1
  • 8

1 Answers1

1

Your loops are totally wrong. for i in [2] just means to loop over that 1-element list, which is no different from just writing i = 2 without any loop.

You should be looping over the list x, which contains the result of reading the file.

for row in x[1:]:
    if str1 == row[0] and str2 == row[1]:
        print("Access granted")
        break
else:
    print("Access not granted")

x[1:] skips over the header line. Notice that the else: block is on the for loop, not the if statement; this runs only if you get to the end of the loop without breaking. If you put it on the if statement, it will report an error for every line in the file that doesn't match; see Searching array reports "not found" even though it's found

Barmar
  • 741,623
  • 53
  • 500
  • 612