python里面遇到 ,这个循环只能让我运行列表里面的三个元素
names=['Tom',"jaden",'ADMIN','WILLIAM','li hua']
#names2=names[:]
if names:
for name in names:
if name.lower() == 'admin':
print('Hello admin,would you like to see a status report?')
else:
print(f"Hello {name.title()},thank you for logging in again")
#names2.remove(name)
names.remove(name)
#print(names2)
#names=[]
print("")
else:
print("We need to find some users!")
Hello Tom,thank you for logging in again
Hello admin,would you like to see a status report?
Hello Li Hua,thank you for logging in again
建立一个新列表names2作为副本,但是不能直接用names2来运行else里面的的代码
names里面每一个元素执行循环后,列表成为空列表,接着执行else,或者能改成elif也行
不要在循环里执行names.remove(name)
你这列表后续又不用它,为什么非要纠结把里面的东西删光,留着碍什么事了?
第5行改成这样即可
for name in names[:]:
循环中删除,导致循环次数和实际元素不匹配(删除元素后,元素的下标都改变了)
按你的需求,循环结束后clear不就都清空元素了吗,这样不可以吗?
另外,进入了if names就不会在进入else,尽管在if里清空了names,因为先进入if,才会有nanes清空,所以,你要再次判断,把else改成if not names,这样,你在第一个if里清空了names,自然就会进入第二个if了