我希望输出在for循环中显示一次



如果Else语句出错,我希望它显示一次。请看我试过的代码。

lists = ['apple','grape','pineapple','orange']
password = "xyz"
def pass1():
for i in lists:
if i == password:
print("Accepted!", "Password : " + i)
break
else:
print("Password not found! Try again")
pass1()

输出:

Password not found! Try again
Password not found! Try again
Password not found! Try again
Password not found! Try again
Process finished with exit code 0

如果我正确理解你的问题,你可以通过删除else来完成,如果循环结束,但你没有在列表中找到密码,那么它就不存在了。

lists = ['apple','grape','pineapple','orange']
password = "xyz"
def pass1():
for i in lists:
if i == password:
print("Accepted!", "Password : " + i)
return
print("Password not found! Try again")
pass1()

另一种更像蟒蛇的方式

def pass2():
if password in lists:
print(print("Accepted!", "Password : " + lists.index(password)))
else:
print("Password not found! Try again")
pass2()

我不明白你为什么不把密码作为参数传递?

也许可以考虑按照来做

def pass3(password, lists):
if password in lists:
print(print("Accepted!", "Password : " + lists.index(password)))
else:
print("Password not found! Try again")
lists = ['apple','grape','pineapple','orange']
password = "xyz"
pass3(password, lists)

实际上,如果你只想检查列表中的值,就不需要循环,只需尝试一下:

def pass1():
if password in lists:
print("Accepted!", "Password : " + password)
else:    
print("Password not found! Try again")

但如果你仍然想迭代列表,你可以使用这样的返回:

def pass1():
for i in lists:
if i == password:
return print("Accepted!", "Password : " + i)
return print("Password not found! Try again")

因为如果不使用return,即使密码为true,最后一个代码仍然会打印出来。

for loop上使用else的另一种方法
else block只有在每个项目都用完时才执行:

lists = ['apple','grape','pineapple','orange']
password = "xyz"
def pass1():
for i in lists:
if i == password:
print("Accepted!", "Password : " + i)
break
else:
print("Password not found! Try again")
pass1()

最新更新