5次尝试后如何退出while-true循环?

时间:2019-03-20 19:01:42

标签: python while-loop

在我对计算机科学课的介绍中,我们遇到一个问题,我们必须创建一个要求输入个人密码的循环:

while True:
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")
print("Welcome!")

我如何更改它,以便在尝试5次/猜测一次密码后,显示“全部出于密码猜测”(或类似性质的东西)?

6 个答案:

答案 0 :(得分:3)

许多人不熟悉awk -F "|" 'NR==FNR {first= $1; second=$2; third=$3;} NR > 1{print "{" first ":" $1 "\n" second ":" $2 "\n" third ": "$3 "}" }' File1.txt File2.txt {CIN:1234 Template:QWERTY Date: 2019-03-18} {CIN:5678 Template:ASDF Date: 2019-03-18} {CIN:9012 Template:ZXCVB Date: } 结构,在这种情况下,这是经典的

for...else

for attempt in range(5): password = input('What is your password?') if password == "abc123": print("Welcome!") break else: print("all out of password guesses") 仅在未遇到else时被执行

答案 1 :(得分:0)

我同意@mauve的观点,where循环并不是您想要的,但是您仍然可以使用计数器来完成它:

while

但是,使用for循环可能会更清晰


max_tries = 5

while max_tries > 0: # We will decrement max_tries on each loop
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")
    max_tries -= 1 # Decrement max_tries

if max_tries==0: # We tried too many times
    raise ValueError("Too many attempts!")

您可以在for循环的末尾使用 for i in range(max_tries): password = input('What is your password?') if password == "abc123": break print("Please Try Again") if i == max_tries: raise ValueError("Too many attempts") ,如下所示:

else

for i in range(max_tries): password = input('What is your password?') if password == "abc123": break print("Please Try Again") else: raise ValueError("Too many attempts") 将捕获在循环结束之前未调用else的情况

答案 2 :(得分:0)

实际上,如果有循环限制,则它不是真正的“ while true”。您只需检查5次(或n次)密码即可达到相同的目的。

try_num = 0
    while try_num <= 5:
        try_num = try_num + 1
        <rest of the code>

如果对于评估者/教师/分配所期望的特定格式,必须有一段时间为True,则仍可以使用此计数器并在while True内中断。

try_num = 0
success = False
    while True:
        try_num = try_num + 1
        password = input('What is your password?')
        if password == "abc123":
            success = True
            break
        if try_num > 5:
            break
        print("Please Try Again")
if success == True:
    print("Welcome!")

您可能会看到选项1更优雅,更易于维护。

答案 3 :(得分:0)

或者,您可以使用while ... else循环:

attempts = 0
while attempts < 5:
    password = input('What is your password?')
    if password == "abc123":
        print("Welcome!")
        break
    print("Please Try Again")
    attempts += 1
else:
    print('You have exceeded the number of allowed login attempts!')

答案 4 :(得分:-1)

制作一个计数器,然后倒数。 while循环的条件应为“当计数器达到0时”:

counter = 5
while counter > 0:
    counter -= 1
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")
print("Welcome!")

与正确设置密码相比,您可能需要重写一些内容,以便在计数器超时时发生不同的事情。


或者,更正确的版本是使用for循环而不是while循环:

for i in range(5):  # will execute 5 times with i = 0, 1, 2, 3, 4 in that order
    ...

但是,如果您没有特别使用i变量,那么while也可以正常工作。

答案 5 :(得分:-1)

不仅在python中,而且在一般编程中,我真的是菜鸟。只是学习而被隔离。我想出了这段代码来完成操作所要求的。我正在上在线课程,而活动要求这样做。 在您看来,这可能很愚蠢,并确保有更好的方法来执行我在此处所做的操作,但这是可行的。 (活动要求在True时进行)

rainbow = ("red, orange, yellow, green, blue, indigo, violet")
while True:
    color_input = input("Enter a color of the rainbow: ")
    if color_input.lower() in rainbow:
        print ("Great, you did it!! ")
        break
    else:
        print ("Wrong, you still have 3 tries.")

        while True:
            color_input = input("Enter a color of the rainbow: ")
            if color_input.lower() in rainbow:
                print ("Great, you did it")
                break
            else:
                print ("Wrong, you stil have 2 tries")

                while True:
                    color_input = input ("Enter a color of the rainbow: ")
                    if color_input.lower() in rainbow:
                        print ("Great, you did it")
                        break
                    else:
                        print ("Wrong, last try")

                        while True:
                            color_input = input("Enter a color of the rainbow: ")
                            if color_input.lower() in rainbow:
                                print ("Great, you finally did it")
                                break
                            else:
                                print ("You ran out attemps. Sorry, you failed")
                                break
                        break
                break
        break
相关问题