我是 python 新手,我正在嘗試構建我的第一個帳戶專案,我允許用戶輸入名稱、用戶名、密碼和其他詳細資訊。要登錄我會詢問用戶用戶名和密碼,我知道如何在特定列中搜索以檢查用戶名是否存在,但我努力尋找的是如何檢查用戶名同一行中的密碼是否是正確,我不希望它在所有密碼列中搜索,只搜索已輸入的用戶名的密碼。我為此使用 open openpyxl。
這是我的代碼
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
這是我做的檢查功能。
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
這是代碼,我想做什么
在此處輸入影像描述 這是表格
uj5u.com熱心網友回復:
如果沒有必要,“做”需要多次處理的事情并不是一個好習慣。應避免對打開 excel 檔案的函式username_check
進行兩次呼叫,因為您可以同時檢查用戶名和密碼。
還要注意 python 代碼中的縮進。
您可以通過使用 zip 同時迭代兩個列來使代碼更簡單、更易于閱讀。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/504065.html