I am new to python and i'm trying to build my first accounts projects, which i allow users to input name, username, password and other details. to sign in i would ask user for username and password, i do know how to search in a specific column to check if the username exist, but what im struggling to find is how to check if the password in the same row of the username is correct, i dont want it to search in all passwords column, only the password of the username that has been entered. i am using open openpyxl for this.
heres my code
def username_check(filename , minrow, maxrow, mincol, maxcol, name):
wd = load_workbook(filename)
ws = wd.active
for row in ws.iter_cols(min_row=minrow,max_row=maxrow,min_col=mincol, max_col=maxcol, values_only=True):
if name in row:
return True
else:
return False
this is the checking function ive made.
while True:
if x == 1:
username = input("enter your account username: ")
password = int(input("enter password: "))
usernamecheck = username_check("accounts.xlsx", 2 , len(ws["C"]), 3, 3, username)
passwordcheck = username_check("accounts.xlsx", 2, len(ws["D"]), 4, 4, password) # This is wrong
if usernamecheck and password == True:
print("ok")
break
this is the code and what im trying to do
enter image description here this is the table
CodePudding user response:
Its not good practice to 'do' things that take a lot of processing more than once if its not necessary.
Making two calls to the function username_check which opens the excel file should be avoided since you can check both the username and password at the same time.
Also be careful of indentation in python code.
You can make the code much simpler and easier to read by using zip to iterate both columns at the same time.
from openpyxl import load_workbook
def username_check(filename, username, password):
wb = load_workbook(filename)
ws = wb.active
for user_col, pass_col in zip(ws['C'], ws['D']):
if user_col.row == 1: # This skips the Header row
continue
if user_col.value == username and pass_col.value == password:
return True
return False
filename = 'accounts.xlsx'
while True:
username = input("enter your account username: ")
password = int(input("enter password: "))
usernamecheck = username_check(filename, username, password)
if usernamecheck:
print("ok")
break