2017-10-21 53 views
1

我已經獲取了一些帶有一些信息的CSV,並且代碼將遍歷CSV中的每一行,並且如果輸入的用戶名與該行中的值匹配,將允許用戶登錄。Python - 在迭代CSV結束時打印消息

但是,我不知道如何讓我的程序說出他們的細節不正確。每次迭代後都會打印出「未找到」,而不是在CSV的末尾。

我怎麼能這樣做,所以一旦它在for循環的結尾,它說明細節沒有找到?

謝謝。

username = str(input("Enter your username: ")) 
password = str(input("Enter your password: ")) 

file = open("details.csv","r") 
print('Details opened') 
contents = csv.reader(file) 
print('reader established') 

for row in contents: 
    print('begin loop') 
    if username == row[4]: 
     print("Username found") 
     if password == row[3]: 
      print("Password found") 
      main() 
    else: 
     print("not found") 

回答

1

簡單的辦法就是添加變量is_found爲例:

is_found = False 

for row in contents: 
    print('begin loop') 
    if username == row[4]: 
     print("Username found") 
     if password == row[3]: 
      print("Password found") 
      main() 
      is_found = True 

if not is_found: 
    print("not found") 
+0

完美的感謝。 – AgentL3r

+0

@Bear發佈你的解決方案對於Python來說太複雜了;) –

2

使用break反正stop using print for debugging

for row in contents: 
    print('begin loop') 
    if username == row[4]: 
     print("Username found") 
     if password == row[3]: 
      print("Password found") 
      main() 
      break 
else: 
    print("not found")