Search code examples
pythonloopsinfinite-loopinfinite

How to fix infinite loop in Python?


I am making a login security program in Python, and this part always gets stuck in in infinite loop. If you get locked out, it keeps saying that 'you have been locked out for 10 seconds' and it loops infinitely. How do I fix this?

tries=0
while finalusername!=username or  finalpassword!=password:
tries=tries+1
print "That incorrect. Try again."
print "You have", 5-tries, "tries left."
finalusername= raw_input ("Username:")
finalpassword= raw_input ("Password:") 
while tries>=4:
    print "You have been locked out for 10 seconds. Please call the administrator if this keeps happening."
    sleep (10.0)
    system ('CLS')
    finalusername!=username
    finalpassword!=password

Solution

  • Your second while loop activates when tries is greater than four, but the loop itself never operates on tries or contains any other exit condition. That is why it becomes infinite. So tries remains above four and the loop never ceases.

    From your code, it seems to me that after they use up their tries, they get locked out for 10 seconds and then they get to start again? If so you would wish to adjust your code like this:

    tries=0
    while finalusername!=username or  finalpassword!=password:
        tries=tries+1
        print "That incorrect. Try again."
        print "You have", 5-tries, "tries left."
        finalusername= raw_input ("Username:")
        finalpassword= raw_input ("Password:") 
        if tries>=4:
            print "You have been locked out for 10 seconds. Please call the administrator if this keeps happening."
            sleep (10.0)
            system ('CLS')
            tries = 0 #Reset tries counter
            finalusername!=username #I don't think this part is required
            finalpassword!=password #I don't think this part is required