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

VBA皮特

我编写了一段简单的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!循环结束时返回

我期望for循环在之后停止,Hello User5因为current_usernames左侧没有更多用户了

疯狂物理学家

循环else子句for在循环正常完成的任何时间触发,而不是通过break语句触发由于您的循环不包含break,因此else总是会触发。

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

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

似乎您混淆了else以下for循环,而else通常在条件语句中发现以下内容可以满足您的要求:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么这个 for 循环返回一个空列表?

为什么ForkJoinPool :: shutdownNow返回一个空列表?

为什么retainAll()返回一个空列表?

为什么我的回溯总是返回一个空列表?

为什么我的函数不断返回一个空列表?

为什么我的递归函数返回一个空列表?

为什么我的循环只返回一个答案而不是整个列表的答案?

为什么我使用 python 构建的 Webscraper 在应该返回抓取的数据时返回一个空列表?

为什么re.split()在结果列表的末尾返回一个额外的空白?

为什么我的 ArrayBlockingQueue 在放入一个列表后会导致一个空队列?

为什么我的LinkedList在列表末尾读取一个额外的节点?

为什么我的代码给我一个值而不是一个列表

为什么我的代码会生成一个空列表列表?

为什么列表保留C#中另一个空列表的值

遍历两个列表并添加到结果列表将返回一个空列表。为什么?

为什么与空列表连接会返回一个列表,而与新列表连接时却不会?

为什么我的循环每隔一个列表条目就会跳过一次?

在Javascript中,为什么Object.getPrototypeOf([1,2])返回一个空列表?

为什么查询Google云文件会返回一个空列表?

为什么包含关键字 IN 的查询总是返回一个空列表?

为什么BeanDefinition.getPropertyValues返回一个空列表

为什么一个空列表在返回时变成NoneType?

我正在尝试返回一个空列表

为什么我的 pygame.group 在循环时有一个空值?

为什么我使用solve命令得到一个空列表作为输出?

当N = 1时,为什么我得到一个空列表而不是[0]

为什么我的for循环在python列表迭代器之后只有一个结果?

为什么它创建一个空列表()

为什么附加到类实例的列表然后从方法返回它会导致一个空列表?