Skip to main content
 首页 » 编程设计

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

2025年05月04日22daizhj

我写了一段简单的 Python 代码,应该比较列表 current_usernames(尝试登录的用户)和列表 usernames(尝试登录的用户)已经登录)。如果来自 current_usernames 的用户已经在 usernames 中,则该用户将被拒绝,否则将迎接该用户。如果 current_usernames 中没有用户,则应该只有一个输出:此时系统中没有用户。

代码:

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 this point!?

我原以为循环会在 Hello User5 之后停止,因为 current_usernames 左边没有更多的用户。

请您参考如下方法:

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

else 子句背后的想法是让编写类似线性搜索的东西更容易:

for x in sequence: 
    if x == key: 
        print('found it') 
        break 
else: 
    print('Not found') 

您似乎混淆了 for 循环之后的 else 和通常在条件语句中找到的 else 以下将执行的操作你想要:

if current_users: 
    for current_user in current_usernames: 
       ... 
else: 
    print('No users currently trying to get into the system')