2017-10-21 52 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")