我编写了一段简单的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] 删除。
我来说两句