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

时间:2020-03-23 23:38:49

标签: python

如果错误,我希望其他语句显示一次。请查看我尝试过的代码。

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

3 个答案:

答案 0 :(得分: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()

另一种更Python化的方式

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)

答案 1 :(得分:0)

实际上,如果您只想检查列表中的值,则不需要循环,只需尝试以下操作:

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

但是如果您仍然想遍历列表,则可以使用return这样:

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

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

答案 2 :(得分:0)

else上使用for loop的另一种方法
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()