我正在創(chuàng)建一個登錄和菜單程序,我有一個 CSV 文件,其中包含我發(fā)明的一些用戶的登錄名和密碼。當(dāng)我運行程序時,它沒有任何錯誤,但是當(dāng)我輸入正確的用戶名和密碼時,它不能正常工作。當(dāng)我的代碼應(yīng)該打印“已授予訪問權(quán)限”時,它會打印“未授予訪問權(quán)限”。這是我在控制臺中打印 CSV 時的樣子:[['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']]這是我現(xiàn)在擁有的代碼:import sysimport csvimport numpy as npdef 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**************")
1 回答

楊__羊羊
TA貢獻(xiàn)1943條經(jīng)驗 獲得超7個贊
你的循環(huán)是完全錯誤的。for i in [2]just 表示循環(huán)遍歷該 1 元素列表,這與僅編寫i = 2沒有任何循環(huán)沒有什么不同。
您應(yīng)該遍歷 list x,其中包含讀取文件的結(jié)果。
for row in x[1:]:
if str1 == row[0] and str2 == row[1]:
print("Access granted")
break
else:
print("Access not granted")
x[1:]跳過標(biāo)題行。請注意,else:塊在for循環(huán)中,而不是if語句;僅當(dāng)您在沒有中斷的情況下到達(dá)循環(huán)末尾時才會運行。如果你把它放在if語句上,它會為文件中不匹配的每一行報錯;即使已找到,請參閱搜索數(shù)組報告“未找到”
添加回答
舉報
0/150
提交
取消