简体   繁体   English

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

[英]How do I exit a while-true loop after 5 tries?

In my introduction to computer science class, we were given a problem where we had to create a loop that asked for a persons password:在我对计算机科学课程的介绍中,我们遇到了一个问题,我们必须创建一个循环来要求输入人员密码:

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

How do I change it so that after 5 tries/guesses of the password, it says "all out of password guesses" (or something of that nature)?我如何更改它,以便在 5 次尝试/猜测密码后,它显示“密码猜测全部结束”(或类似的东西)?

Many people are not familiar with the for...else construct, that is classic in this case很多人不熟悉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")

The else get executed only if a break is not encountered只有在没有遇到break才会执行else

I'd agree with @mauve that a while loop isn't exactly what you are looking for, but you can still do it with a counter:我同意@mauve 的观点,即while循环并不是您要查找的内容,但您仍然可以使用计数器来实现:


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!")

However, it might be a bit clearer to use a for loop但是,使用 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")

You could use an else at the end of your for loop like so:您可以在 for 循环的末尾使用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")

Where the else will catch the case where a break wasn't called before the end of the loop else将捕获在循环结束之前没有调用break的情况

In effect it is not a truly "while true" if you have a looping limit.实际上,如果您有循环限制,它就不是真正的“while true”。 You could achieve the same thing by simply checking for password 5 (or n times).您可以通过简单地检查密码 5 次(或 n 次)来实现相同的目的。

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

If you must have a while True for a specific format expected by the evaluator/teacher/assignment, you could still use this counter and break inside the while True .如果对于评估者/教师/作业所期望的特定格式,您必须有一个 while 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!")

You may see that option 1 is more elegant and simpler to maintain.您可能会看到选项 1 更优雅且更易于维护。

Alternatively you can use while ... else loop:或者,您可以使用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!')

Make a counter , and have it count down.做一个计数器,让它倒计时。 The condition of the while loop should be "when the counter hits 0": 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!")

You might need to rewrite some things in order to have different things happen when you time out with the counter, compared to getting the password correct.与正确获取密码相比,您可能需要重写一些内容,以便在计数器超时时发生不同的事情。


Alternatively, a more correct version would be to use a for loop instead of a while loop:或者,更正确的版本是使用for循环而不是while循环:

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

but if you're not using the i variable for anything in particular, a while will work just as well.但是如果您没有将i变量用于任何特别的事情,那么一段while也可以正常工作。

I'm really noob not only in python but in programming in general.我真的不仅在 python 中而且在编程方面都是菜鸟。 Just learning while quarentined.只是在隔离期间学习。 I came up with this code to do what the op asked for.我想出了这个代码来完成操作的要求。 I'm doing an online course and the activity asked for it.我正在做一个在线课程和活动要求它。 It may look stupid to you and sure there are better ways to do what I did here, but this works.这对您来说可能看起来很愚蠢,并且肯定有更好的方法来做我在这里所做的事情,但这是有效的。 (the activity asked to do it whith While True) (该活动要求使用 While 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM