为什么我的for循环在列表末尾返回一个空列表值?

时间:2018-12-03 06:32:36

标签: python

我编写了一段简单的Python代码,该代码应该将列表current_usernames(正在尝试登录的用户)与列表usernames(已经登录的用户)进行比较。如果来自current_usernames的用户已经在usernames中,则该用户将被拒绝,否则将向该用户打招呼。如果current_usernames中没有用户,则应该只有一个输出: There are no users in the system at this point

代码

usernames = ["User1", "User2", "User3", "User4", "User5", "Admin"]
current_usernames = ["User6", "User7", "User3", "User8", "User5"]

for current_user in current_usernames:
    if current_user not in usernames:
        if current_user == "Admin":
            print("Hello Admin!!! Welcome back!")
        else:
            print("Hello " + current_user)
    else:
        print("Sorry, " + current_user + " is already logged in.")
else:
    print("There are no users in the system at this point!")

输出:

Hello User6 
Hello User7
Sorry, User3 is already logged in.
Hello User8
Sorry, User5 is already logged in.
There are no users in the system at this point!

问题:

为什么for循环在循环结束时返回 There are no users in the system at this point!

我期望Hello User5之后for循环会停止,因为剩下的current_usernames中没有更多用户。

1 个答案:

答案 0 :(得分:5)

循环else的{​​{1}}子句通常在循环正常完成的任何时间触发,而不是通过for语句触发。由于您的循环不包含break,因此break将始终被触发。

else子句背后的想法是使编写线性搜索之类的内容更加容易:

else

您似乎将for x in sequence: if x == key: print('found it') break else: print('Not found') 循环后的else与通常在条件语句中发现的for混淆了,下面的命令可以满足您的要求:

else