如何在Python中修复无限循环?

时间:2015-11-07 03:03:22

标签: python loops infinite-loop infinite

我正在用Python创建一个登录安全程序,这个部分总是陷入无限循环中。如果你被锁定,它会一直说“你被锁定了10秒钟”并且无限循环。我该如何解决这个问题?

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

3 个答案:

答案 0 :(得分:0)

轻松,改变

  while tries>=4:

  if tries >= 4:

如果你按照你的代码,当你进入第二个while循环时,变量尝试的值永远不会改变,所以你将永远留在那里。如果将while更改为if,则将执行if语句的主体,然后继续循环。

答案 1 :(得分:0)

while大于4时,您的第二个tries循环会激活,但循环本身永远不会在tries上运行或包含任何其他退出条件。这就是为什么它变得无限。所以tries仍然高于4,循环永远不会停止。

从您的代码中,在我看来,在他们用尽了他们的尝试之后,他们被锁定了10秒然后他们又重新开始了?如果是这样,您希望像这样调整您的代码:

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

答案 2 :(得分:0)

我认为你应该在睡眠后将尝试设置为0,如果没有必要则设置循环。睡眠后,用户应再次尝试5次。

import os
import time

tries=0
finalusername, finalpassword= 'a', 'a'
username, password = None, None


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