简体   繁体   中英

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)?

Many people are not familiar with the for...else construct, that is classic in this case

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

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:


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 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 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

In effect it is not a truly "while true" if you have a looping limit. You could achieve the same thing by simply checking for password 5 (or n times).

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 .

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.

Alternatively you can use while ... else loop:

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":

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 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'm really noob not only in python but in programming in general. 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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